Skip to content

C Input/Output (I/O)

Input/Output in C is performed using functions from the <stdio.h> (Standard Input/Output) library.

FunctionPurpose
printf()Prints output to the console
scanf()Reads input from the keyboard
fprintf()Writes output to a file
fscanf()Reads input from a file
sprintf()Writes formatted output to a string
sscanf()Reads formatted input from a string

A format specifier begins with % and tells the compiler the data type of the value to print or read.

SpecifierData Type
%dint
%uunsigned int
%cchar
%sString (char[])
%ffloat (scanf), float/double (printf)
%lfdouble (scanf)
%xHexadecimal
%oOctal
%pPointer (memory address)
%%Prints %

printf() is used to display formatted output on the console.

Syntax

printf("format_string", arguments);

Example

int age = 20;
float cgpa = 8.7;
char grade = 'A';
printf("Age = %d\n", age);
printf("CGPA = %f\n", cgpa);
printf("Grade = %c\n", grade);

Important Notes

  • Pass values, not addresses.
  • Uses format specifiers to determine how data is printed.
  • float is automatically promoted to double, so both float and double use %f.
float f = 3.5;
double d = 3.5;
printf("%f\n", f);
printf("%f\n", d);

scanf() is used to read formatted input from the keyboard.

Syntax

scanf("format_string", &variable);

Example

int age;
float cgpa;
scanf("%d", &age);
scanf("%f", &cgpa);

Important Notes

  • Pass the address of variables using &.
  • scanf() stores the user’s input in the given memory location.
  • float uses %f, while double uses %lf.
float f;
double d;
scanf("%f", &f);
scanf("%lf", &d);

printf() requires the value

printf() only reads the value and prints it.

int x = 10;
printf("%d", x);

Here, x (value 10) is passed.

scanf() requires the address

scanf() needs to store the input into the variable, so it requires the variable’s memory address.

int x;
scanf("%d", &x);

Here, &x (address of x) is passed.

x → Value stored in the variable
&x → Memory address of the variable

Example:

int x = 25;
x = 25
&x = 0x61FF08 // Example address

For arrays, the array name itself represents the address of its first element.

char str[20];
scanf("%s", str);
printf("%s", str);

Here,

str == &str[0]

Therefore,

scanf("%s", str); // Correct
scanf("%s", &str); // Incorrect
%d // int
%u // unsigned int
%c // char
%s // string
%f // float (scanf), float/double (printf)
%lf // double (scanf)
%x // hexadecimal
%o // octal
%p // pointer (address)
%% // prints %
  • printf() → Displays output → Pass values.
  • scanf() → Reads input → Pass addresses using &.
  • Exception: Arrays (e.g., strings) do not use & because the array name is already an address.
  • In printf(), both float and double use %f.
  • In scanf(), float uses %f and double uses %lf.
  • Always use the correct format specifier to match the variable’s data type.