printf( ) and scanf( ) With Example

how printf and scanf works

printf() and scanf() functions are inbuilt library functions in C programming language which are available in C library by default. These functions are declared and related macros are defined in “stdio.h” which is a header file in C language.

printf() function in C language:

  • In C programming language, printf() function is used to print the “character, string, float, integer, octal and hexadecimal values” onto the output screen.
  • We use printf() function with a %d format specifier to display the value of an integer variable.
  • Similarly, %c is used to display character, %f for float variable, %s for a string variable, %lf for double, and %x for the hexadecimal variable.
  • To generate a newline, we use “n” in C printf() statement.
printf and scanf

printf syntax:

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

Example:

#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("a=10, b=20");
return 0;
}

Output:

a=10, b=20

scanf() function in C language:

  • In C programming language, scanf() function is used to read character, string, numeric data from the keyboard
  • Consider the below example program where the user enters a character. This value is assigned to the variable “ch” and then displayed.
  • Then, the user enters a string and this value is assigned to the variable “str” and then displayed.
  • It is used for taking input from users.

scanf: Scan in a file. Denoted by & that’s called address.

scanf syntax in C:

#include <stdio.h>
#include <stdlib.h>
int main()
{
int x;
scanf("%d",&x);
printf("Format specifers %d",x);
return 0;
}

Example:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int x;
    printf("Enter a number\n");
    scanf("%d",&x);
    printf("Number is: %d",x);
return 0;
}
 

Output:

Enter a number
5
Number is: 5

When the user puts 5 value then printf shows 5 in output.

Previous Lecture:

Introduction to C
Escape Characters
Data Types

If you have any problem in solving your questions, then join our Telegram group or search @Learnsimply, we will help you.

Please write comments if you find anything incorrect in the printf() and scanf() lecture.

Leave a Comment

en English
X