Friday, August 21, 2009

Printf and Scanf

Printf
Used for formatted output in C.
Writes formatted data to the monitor
Printf needs two things
  • Instruction for formatting the data and
  • The actual data to be printed

Example:
          int a;
          char b;
          float c;
          double d;

          printf("%d %c %f %lf", a, b, c, d);

Conversion Code:

int           %d
char        %c
float        %f
double    %lf

Scanf
Used for formatted input in C.
Reads formatted data from the keyboard
It consists of two parts
  • A format string that describes the data and
  • an address list that identifies where data are to be placed in memory
scanf requires that variables in the address list be represented by their address.
To specify an address, you prefix the variable name with the address operator, the ampersand (&)

Example
          int a;
          char b;
          float c;
          double d;

          scanf("%d %c %f %lf", &a, &b, &c, &d);

No comments: