Console I/O Functions in C

The screen and keyboard together are called a console. Console I/O functions can be further classified into two categories— formatted and unformatted console I/O functions. The basic difference between them is that the formatted functions allow the input read from the keyboard or the output displayed on the VDU to be formatted as per our requirements. For example, if values of average marks and percentage marks are to be displayed on the screen, then the details like where this output would appear on the screen, how many spaces would be present between the two values, the number of places after the decimal points, etc. can be controlled using formatted functions.

Console IO Functions in C
Console IO Functions in C

Formatted Console I/O Functions

the functions printf( ), and scanf( ) fall under the category of formatted console I/O functions. These functions allow us to supply the input in a fixed format and let us obtain the output in the specified form.

printf ( "format string", list of variables ) ; 

The format string can contain:

  • Characters that are simply printed as they are
  • Conversion specifications that begin with a % sign
  • Escape sequences that begin with a \ sign

For example

main( ) 
{ 
 int avg = 346 ; 
 float per = 69.2 ; 
 printf ( "Average = %d\nPercentage = %f", avg, per ) ; 
} 

The output of the program would be…

Average = 346 
Percentage = 69.200000

Format Specifications

The %d and %f used in the printf( ) are called format specifiers. They tell printf( ) to print the value of avg as a decimal integer and the value of per as a float. Following is the list of format specifiers that can be used with the printf( ) function.

Format Specifications
Format Specifications
Format Specifications
Format Specifications

Example

main( ) 
{ 
 int weight = 63 ; 
 printf ( "\nweight is %d kg", weight ) ; 
 printf ( "\nweight is %2d kg", weight ) ; 
 printf ( "\nweight is %4d kg", weight ) ; 
 printf ( "\nweight is %6d kg", weight ) ; 
 printf ( "\nweight is %-6d kg", weight ) ; 
}

The output of the program would look like this

Columns 0123456789012345678901234567890 
 weight is 63 kg 
 weight is 63 kg 
 weight is 63 kg 
 weight is 63 kg 
 weight is 63 kg 

Leave a Comment