top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

    Get Free Article Updates

Facebook Login
Site Registration
Print Preview

C# Console Input Operations

0 votes
8 views

                    Console Input Operations                                        

Input Methods

In C# to read data, you need the standard input stream. This stream is provided by the input methods of the Console class. There are two input methods that enable the software to take in the input from the standard input stream. These methods are:

  • Console.Read() : Reads a single character
  • Console.ReadLine(): Reads a line of strings

Example:

Class StudentDetails

{

    Static void main (string [] args)

   {

      string name;

      Console.WriteLine(“ Enter your name:”);

      name = Console.ReadLine();

      Console.WriteLine(“ You are{0}”, name);

     }

}

Output:

In the above code, the ReadLine() method reads the name as the string. The sting that is given is displayed as output using placeholders.

 

Convert Methods

The ReadLine() method can also be used to accept integer values from the user. The data is accepted as a string and then converted into the int data type. C# provides a convert class in the system namespace to convert one base data type to another base data type.

                                          

Example:

The following snippet reads the name, age and salary using the Console.ReadLine() method and converts the age and salary into int and double using the appropriate convertsion methods of the convert class.

string userName;

int age;

double salary;

Console.Write( “Enter your name:”);

userName= Console.ReadLine();

Console.Write(“Enter your age:”);

age = Convet.ToInt32 (Console.ReadLine());

Console.Write(“Enter  the salary: “);

Salary = Convet.ToDouble(Console.ReadLine()));

Console.WritLine (“Name: {0}, Age:{1}, Salary: {2} “, userName, age, salary);

Output:

Enter your name: David Blake

Enter your age: 34

Enter the salary: 3450.50

Name: David Blake, Age: 34, Salary: 3450.50

More: The Convert.ToInt32() method converts a specified value to an equivalent 32-bit signed integer, Convet.ToDecimal() method converts a specified value to an equivalent decimal number. 

Go through this tutorial video:

posted 6 days ago by Naziya Raza Khan

  Promote This Article
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button


Related Articles

Console Output Operations

Console Operations  are tasks performed on the command line interface using executable commands. The console operations are used in software applications because these operations are easily controlled  by the operations are dependent on the input and output devices of the computer system.

A console application is one that performs operations at the command prompt. All console applications consists of three streams, which are a series of bytes. These streams are attached to the input and output devices of the computer system and they handle the input and output operations. Three streams are:

  • Standard in: The standard in stream takes the input and passes it to the console application for processing.
  • Standard out: The standard out stream displays the output o the monitor.
  • Standard err: The standard err stream displays error messages on the monitor.

                      

Output Methods

In C#, all console operations are handled by the console class of the System namespace. A namespace is a collection of classes having similar functionalities.

To write data on the console, you need the standard output stream. This stream is provided by the output methods of console class. There are two output methods that write to the standard output stream. They are:

  • Console.Write(): Writes any type of data.
  • Console.WriteLine(): Writes any type of data and this data ends with a new line character in the standard output stream. This means any data after this line will appear on the new line.

                                                       

The following syntax is used for the Console.Write() method, which allows you to display the information on the console window.

Console.Write(“<data>” + variables);

Where,

Data: Specifies strings or escape sequence characters enclosed in double quotes.

Variables: Specify variable names whose value should be displayed on the console.

The following syntax is used for the Console.WriteLine() method, which allows you to display the information on new line in the console window.

Console.WriteLine(“<data>” + variables);

The following code shows the difference between the console.write() method and Console.WriteLine() method.

Console.WriteLine(“C# is a powerful programming language”);

Console.WriteLine(“C#  is a powerful”);

Console.WriteLine(“Programming language”);

Console.Write(“C# is a powerful”);

Console.WriteLine(“Programming language”);

Output:

C# is a powrful programming language

C# is a powerful

Programming language

C# is a powerful Programming language

Placeholders

The WriteLine() and Write() methods accept a list of parameters to format text before displaying the output. The first parameter is a string containing markers in braces to indicate the position where the values of the variables will be substituted. Each marker indicates a zero-based index based on the number of variables in the list. For example, to indicates a zero-based index based on the number of variables in the list. For example, to indicate the first parameter position, you write {0}, second you write {1} and so on. The numbers in the curly brackets are called placeholders.

Example:

int number, result;

number =5;

result =100 * number;

Console.WriteLine (“Result is {0} when 100 is multiplied by {1}”,result, number);

result = 150 / number;

Console.WriteLine (“Result is {0} when 150 is divided by {1}”, +result, number);

Output:

Result is 500 when 100 is multiplied by 5

Result is 30 when 150 is divided by 5

Here, {0} is replaced with the value in result and {1} is replaced with the value in number.

READ MORE

Define Numeric Format specifiers

Format specifiers are special characters that are used to display values of variables in a particular format. For example, you can display an octal value as decimal using format specifiers.

In C#, you can convert  numeric values in different  formats. For example, you can display a big number in an exponential form. To convert numeric values using numeric format specifiers, you should enclose the specifier in curly braces. These curly braces must enclosed in double quotes. This is done in the output methods of the console class.

The following is the syntax for the numeric format specifier

Console.WriteLine(“(format specifier)”, variable name>);

Where,

Format specifier: Is the numeric format specifier.

Variable name: Is the name of the integer variable.

Some Numeric Format Specifiers

Numeric format specifiers work only with numeric data . A numeric format specifier can be suffixed with digits. The digits specify the number of zeros to be inserted after the decimal location. For example, if you use a specifier such as c3, three zeros will be suffixed after the decimal location of the given number.

Format Specifier

Name

Description

C or c

Currency

The number is converted to a string that represents a currency amount.

D or d

Decimal

The number is converted to a string of decimal digits (0-9), prefixed by a minus sign is case the number is negative. The precision specifier indicates the minimum number of digits desired in the resulting string. This format is supported for fundamental types only.

E or e

Scientific (Exponential)

The number is converted to a string of the form “-d.ddd…e+ddd”, where each ‘d’ indicates a digit (0-9).

 

The following snippet demonstrates the conversion of a numeric value using C,D and E format specifiers.

int  num =456;

console.WriteLine (“{0:C}”, num);

Console.WriteLine (“{0:D}”, num);

Console.WriteLine (“{0:E}”), num);

Output:

$456.00

456

4.560000E+002

Format Specifier

Name

Description

F or f

Fixed-point

The number is converted to a string of the fomr “-ddd.ddd…” where each ‘d’ indicates a digit (0-9). If the number is negative, the string starts with minus sign.

N or n

Number

The number is converted to a string of the form “-d,ddd,ddd.ddd…”. If the number is negative the string starts with a minus sign.

X or x

Hexadecimal

The number is conveted to a string of hexadecimal digits. Uses “X” to produce “ABCDEF”, AND “x” to produce “abcdef”.

 

The following snippet demonstrates the conversion of the numeric value using F, N and X format specifiers.

int num =456;

Console.WriteLine(“{0:F}”, num);

Console.WriteLine(“{0:N}”, num);

Console.WriteLine(“{0:X}”, num);

Output

456.00

456.00

1CB

READ MORE

Introduction to c#

C# was developed to provide the following benefits:

  • Created a very simple and yet powerful tool for building inter-operable, scalable, robust applications
  • Create a complete object-oriented architecture.
  • Support powerful component-oriented development.
  • Allow access to many features previously available only in c++ while retaining to ease-of-use of a rapid application development tool such as Visual Basic.
  • Provide familiarity to programmers coming from c or c++ background.
  • Allow to write applications that target both desktop and mobile devices.

Purpose of c# language

Microsoft.NET was formerly known as Next Generation Windows Service (NGWS). It is completely new platform for developing the next generation of windows/web applications. These applications would transcend devices boundaries and fully harness the power of the Internet. However, the new platform required a language that could take its full advantage. This is one of the factors that led to the development of c#.

C# is an object-oriented language derived from c and c++. The goal of c# is to provide a simple, efficient, productive, object-oriented language that is familiar and yet at the same time revolutionary.

.NET Framework Fundamentals

The .NET Framework is an essential windows component for building and running the next generation of software applications and XML web services.

The .NET Framework is designed to:

  • Provide consistent object-oriented programming environment
  • Minimize software deployment and versioning conflicts by providing a code-execution environment.
  • Promote safe execution of code by providing a code-execution environment.
  • Provide a consistent developer experience across varying types of application such as windows-based applications and web-based applications.

.NET Framework Components

The .NET Framework has two principal components. They are:

1. The Common Language Runtime (CLR)

The common language runtime is the backbone of .NET Framework. It performs various functions such as:

  • Memory Management
  • Code execution
  • Error handling
  • Code safety verification
  • Garbage collection

2. The .NET Framework Class Library (FCL)

The class library is a comprehensive object-oriented collection of reusable types. It I used to develop applications ranging from traditional command-line to graphical user interface (GUI) applications that can be used on the web.

READ MORE


Here I will explain what is delegates in c#.net with example. Basically delegates in c# are type safe objects which are used to hold reference of one or more methods in c#.net. Delegates concept will match with pointer concept of c language.

Whenever we want to create delegate methods we need to declare with delegate keyword and delegate methods signature should match exactly with the methods which we are going to hold like same return types and same parameters otherwise delegate functionality won’t work if signature not match with methods.

 

Syntax of Delegate & Methods Declaration

public delegate int Delegatmethod(int a,int b);

public class Sampleclass

{

public int Add(int x, int y)

{

return x + y;

}

public int Sub(int x, int y)

{

return x + y;

}

}

 

If you observe above code I declared Delegatmethod method with two parameters which matching with methods declared in Sampleclass class.

 

Complete Example

public delegate int DelegatSample(int a,int b);

public class Sampleclass

{

public int Add(int x, int y)

{

return x + y;

}

public int Sub(int x, int y)

{

return x - y;

}

}

class Program

{

static void Main(string[] args)

{

Sampleclass sc=new Sampleclass();

 

DelegatSample delgate1 = sc.Add;

int i = delgate1(10, 20);

Console.WriteLine(i);

DelegatSample delgate2 = sc.Sub;

int j = delgate2(20, 10);

Console.WriteLine(j);

}

}

Output

Add Result : 30

Sub Result : 10

 

What is the use of Delegates?

 

Suppose if you have multiple methods with same signature (return type & number of parameters) and want to call all the methods with single object then we can go for delegates.

 

Delegates are two types

 

      -   Single Cast Delegates

      -  Multi Cast Delegates

 

Single Cast Delegates

 

Single cast delegate means which hold address of single method like as explained in above example.

 

Multicast Delegates

 

Multi cast delegate is used to hold address of multiple methods in single delegate. To hold multiple addresses with delegate we will use overloaded += operator and if you want remove addresses from delegate we need to use overloaded operator -=

 

Syntax of Multicast Delegate & Method Declaration

public delegate void MultiDelegate(int a,int b);

public class Sampleclass

{

public static void Add(int x, int y)

{

Console.WriteLine("Addition Value: "+(x + y));

}

public static void Sub(int x, int y)

{

Console.WriteLine("Subtraction Value: " + (x - y));

}

public static void Mul(int x, int y)

{

Console.WriteLine("Multiply Value: " + (x * y));

}

}


if you observe above code I declared MultiDelegate method with void return type.

Complete Example

 

 

public delegate void MultiDelegate(int a,int b);

public class Sampleclass

{

public static void Add(int x, int y)

{

Console.WriteLine("Addition Value: "+(x + y));

}

public static void Sub(int x, int y)

{

Console.WriteLine("Subtraction Value: " + (x - y));

}

public static void Mul(int x, int y)

{

Console.WriteLine("Multiply Value: " + (x * y));

}

}

class Program

{

static void Main(string[] args)

{

Sampleclass sc=new Sampleclass();

MultiDelegate del = Sampleclass.Add;

del += Sampleclass.Sub;

del += Sampleclass.Mul;

del(10, 5);

Console.ReadLine();

}

}

 

Output: Whenever we run above code we will get output like as shown below

Addition Value:15

Subtraction Value: 5

Multiply Value:50

READ MORE
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#470/147, 3rd Floor, 5th Main,
HSR Layout Sector 7,
Bangalore - 560102,
Karnataka INDIA.
QUERY HOME
...