Input/output operation in C
 

  • The C standard library contains functions to support writing C programs

  • The scanf( ) function in the C standard library provide input support for data entry (conversion !) using the keyboard

  • The printf( ) function in the C standard library provide output support for data output (conversion !) to the terminal

Printing variables to the terminal output
 

  • The printf( ) function is used to print values of all primitive data types to the terminal

  • The syntax of the printf( ) function is as follows:

       printf("formatString", value1, value2, ... );  
      

  • The "formatString" can contain format conversion fields where value1, value2, etc will be placed

Commonly used format conversions
 

Formatting character Meaning
%d Print the (next) value as a signed decimal integer value
%u Print the (next) value as a unsigned decimal integer value
%ld Print the (next) value as a long signed decimal integer value
%lu Print the (next) value as a long unsigned decimal integer value
%f Print the (next) value as a floating point value
%lf Print the (next) value as a double precision floating point value
%o Print the (next) value as a octal based number
%x Print the (next) value as a hexadecimal based number
%p Print the address (pointer) as a hexadecimal based number
%c Print the (next) value as a character (i.e., used the ASCII code)
%s Print the (next) value as a string (will be explained much later)
%% Print a % character

Example of using the printf( ) function

Example:

#include <stdio.h>

int main( int argc, char* argv[] )
{
   int  x;

   x = 65;     // ASCII code for 'A'
   printf( "x = 65:  %d, %u, %c\n", x, x, x); // Same values !

   x = -1;
   printf( "x = -1:  %d, %u, %c\n", x, x, x);
}

Output: 
   x = 65:   65,  65,           A
   x = -1:   -1,  4294967295,   ??? 

DEMO:   /home/cs255001/demo/tmp/demo.c

Reading input into variables from the keyboard
 

  • The scanf( ) function is used to read values from the keyboard into program variables of any primitive data types

  • The syntax of the scanf( ) function is as follows:

       scanf("formatString", &var1, &var2, ... );  
      

  • The "formatString" can contain format conversion fields to convert ASCII keyboard input into the correct internal representation for var1, var2, etc

Note: I will explain why you need to use the & symbol later !

Example of using the scanf( ) function
 

Example:

 #include <stdio.h>

 int main( int argc, char* argv[] )
 {
    int i;      
    float x;

    printf( "Enter an integer value:");
    scanf( "%d", &i );  // Must use %d to read int value 
    printf( "i = %d\n", i);

    printf( "Enter a floating point value:");
    scanf( "%f", &x ); // Must use %f to read float value
    printf( "x = %f\n", x);
 }
   

DEMO:   /home/cs255001/demo/tmp/demo.c