Printf() and scanf() in c program

The standard input-output header file, named stdio.h contains the definition of the functions printf() and scanf(), which are used to display output on screen and to take input from user respectively.

#include<stdio.h>
void main()
{
    // defining a variable
    int i;
    /*
        displaying message on the screen
        asking the user to input a value
    */
    printf("Please enter a value...");
    /*
        reading the value entered by the user
    */
    scanf("%d", &i);
    /*
        displaying the number as output
    */
    printf( "You entered: %d", i);
}

Output :
Please enter a value...
(Suppose we entered 10)
You entered: 10

When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered on screen.

You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is known as format string and this informs the scanf() function, what type of input to expect and in printf() it is used to give a heads up to the compiler, what type of output to expect

  • %d : Scan or print an integer as signed decimal number
  • %f : Scan or print a floating point number
  • %c : To scan or print a character
  • %s : To scan or print a character string. The scanning ends at whitespace.

NOTE : printf() function returns the number of characters printed by it, and scanf() returns the number of characters read by it.

Post a Comment

If you have any doubts, Please let me know
Thanks!

Previous Post Next Post