C – Input output(I/O): printf, scanf, getchar & putchar

Input output(I/O)

Input means providing or inserting some data that is to be used in a program.
Output means to display the data on the screen or write it in a file.

There are many C built-in function that are used to take in data and display the data from a program as a result.

printf() and scanf() functions

printf() and scanf() are a C built in function whose definition are present in the standard input-output header file, named stdio.h.

printf() takes the values given to it and display it on a screen.
scanf() is used to take in user input and store it in some variable to use it in a program.

Example to show the use of printf() and scanf() in a C program:

#include <stdio.h>

void main()
{
  //defining a variable
  int i;

  /*Displaying to the user to enter value */
  printf("Enter the Value: ");

  /*reading the value*/
  scanf("%d", &i);

  /*Displaying the entered number as a output.*/
  printf("\nEntered number is: %d", i);
}

The output of printf() and scanf() in C.

Enter the Value: 489

Entered number is: 489

The following table shows the use of %d, %f, etc in a above program.

Format StringMeaning
%dScan or print an integer as signed decimal number
%fScan or print a floating point number
%cscan or print a character
%sscan or print a character string

getchar() & putchar() functions

getchar() is used to read a character from the terminals(keyboard) and reads only a single character at a time.
putchar() is used to write a character on the screen. This is mainly used in File handling in C.

Both the function only displays one character at a time so if the user needs to display it more than one time then it needs to be used with loops.

Example to show the use of getchar() & putchar() in a C program:

#include <stdio.h>

void main()
{
  int ch;
  printf("Enter a character you want: ");

 //taking character as an input
  ch = getchar();

  printf("The Entered character is: ");
 //Display the character
  putchar(ch);
}

The output of getchar() & putchar() in C.

Enter a character you want: A
The Entered character is: A