Input Output in C

As we learnt in the previous section, that in C programming language header file i.e. stdio.h contains printf() and scanf() function which we use to take input from the user and print it on the output screen. Now in this section, we will understand the printf() and scanf() function briefly.

print() function

It is an inbuilt library function used in C language that is used to print the character, string, float, integer, octal and hexadecimal values on the output screen. It is mostly used for displaying the formatted output to the screen.

Let’s take an example to understand how printf() works:

Sample code:

#include<stdio.h>    
int main()
{    
printf("Hello");    
return 0;   
}

Output:

Hello

In the above code, the printf() function inside the body of function main() prints the message ‘Hello’ on the output screen.

scanf() function

It is an inbuilt library function used in C language that is used to read character, string, numeric data to be used in a program from the user. It is used to take input from the user during the execution of the program.

Let’s take an example to understand how scanf() works:

Sample code:

#include <stdio.h>
int main()
{
    int age;
    printf("Enter your age - ");
    scanf("%d", &age);  
    printf("Your are %d years old.",age);
    return 0;
}

Output:

Enter your age - 23
Your are 23 years old.

In line 6 of the example above, scanf() function reads input entered by the user, and using printf() function the output is displayed on the screen. We use format specifier (e.g.- %d for int, %c for char, %f for float, etc) to take input from the user and store it in the variable.