top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Console Output Operations in C#

0 votes
518 views

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.

posted Aug 10, 2017 by Naziya Raza Khan

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

                    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:

https://www.youtube.com/watch?v=QzDbwqhGnZA

READ MORE

Standard Date and Time Format Specifiers

 A Date and time format specifier is a special character that enables you to display the date and time values in different formats. For example, you can display a date in mm-dd-yyyy format and time in hh:mm format. If you are displaying  GMT time as the output, you can display the GMT time along with the abbreviation GMT using date and time format specifiers.

The date and time format specifiers allow you to display the date and time and time in 12-hour and 24-hour formats.

The following is the syntax for date and time format specifiers.

Console.WriteLine(“{format specifier}”, <datetime object>);

Where,

Format specifier: Is the date and time format specifier.

Datetime object: Is the object of the DateTime class.

Some Standard date and time specifiers are used in the Console.WriteLine() method with the datetime object. To create the datetime object, you must create an object of the DateTime class and initialize it. The formatted date and time are always displayed as string in the console window.
                                                                                                      

 

The table shown below displays some of the standard date and time format specifiers in C#.

Format Specifier

Name

Description

  D

Long date

Displays date in long date pattern. The default format is “dddd*, MMMM*, dd, yyyy”.

  d

Short date

Displays date in short date pattern. The default format is “mm/dd/yyyy”

  f

Full date/time (short time)

Displays date in long date and short time patterns,, separated by a space. The default format is “dddd*”, MMMM* dd, yyyy HH*:mm*”.

  F

Full date/time (long time)

Displays date in long date and long time patterns, separated by a space. The default format is “dddd*, MMMM* dd,,yyyy HH*: mm*: ss*”.

  G

General date/time (short time)

Displays date in short date and short time patterns, separated by a space. The default format is “MM/dd/yyyy  HH*:mm*”.

 

The following snippet demonstrates the conversion of a specified date and time using the d,D,f,F and g date and time format specifiers:-

DateTime dt =  DateTime.Now;

//Returns short date (MM/DD/YYYY)

Console.WriteLine("Short date format (d): {0:d}",dt);

//Returns long date (Day, Month Date, Year)

Console.WriteLine("Long date format (D) : {0:D}", dt);

//Returns full date with time and without seconds

Console.WriteLine("Full date with time without seconds (f) : {0:f}", dt);

//Returns full date with time and with seconds

Console.WriteLine ("Full date with time with seconds (F) : {0:F}", dt);

//Returns short date and short time without seconds

Console.WriteLine ("Short date and short time without seconds (g) : {0:g}", dt);

 

Output:

Short date format (d) : 23/06/2017

Long date format  (D) : Friday, June 23, 2017

Full date with time without seconds (f) : Friday, June 23, 2017 11:12 AM

Full date with time with seconds (F): Friday, June 23, 2017 11:12:34 AM

Short date and short time without seconds (g): 23/06/2017 11:12 AM

 

More Standard Date and Time Format Specifiers

Format Specifier Name   Description
  G General date/time (long time)  Displays date in short date and long time patterns, separated by a space. The default format is "MM/dd/yyyy HH*:mm*:ss*".
 m or M Month day Displays only month and day of the date.The default format is "MMMM* dd".
  tShort time Displays time in short time pattern.The default format is "HH*:mm*".
  TLong time Displays time in long time pattern. The default format is "HH*:mm*:ss*".
 y or YYear month pattern Displays only month and year from the date.he default format is "YYYY MMMM*".
   

 

The following snippet demonstrates the conversion of a specified date and time using the G,m,t,T :-

DateTime dt = DateTime.Now;

//Returns short date and short time with seconds

Console.WriteLine ("Short date and short time with seconds (G) : {0:G}",dt);

//Returns month and day -M can also be used 

Console.WriteLine ("Month and day (m) : {0:m}", dt);

//Returns short time 

Console.WriteLine("Short time (t) : {0:t}", dt);

 

//Returns short time with seconds

Console.WriteLine("Short time with seconds (T) : {0:T}", dt);

//Returns year and month -Y also can be used 

Console.WriteLine ("Year and Month (y): {0:y}" dt);

Output:

Short date and short time with seconds (G): 23/06/2017 11:40:55 AM

Month and day (m) : June 23

Short time (t) : 11:40 AM

Short time with seconds (T): 11:40:55 AM

Year and Month (y): June , 2017 

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


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
...