In C programming language, scanf() function is used to read character, string, numeric data from keyboard.

Consider below example program where user enters a character. This value is assigned to the variable "ch" and then displayed.

Then, user enters a string and this value is assigned to the variable "str" and then displayed.

  • Exmaple of printf() AND scanf() function in C

    Example)
    drag_handle
     
    #include <stdio.h>
    int main()
    {
       char ch;
       char str[100];
       printf("Enter any character \n");
       scanf("%c", &ch);
       printf("Entered character is %c \n", ch);
       printf("Enter any string ( upto 100 character ) \n");
       scanf("%s", &str);
       printf("Entered string is %s \n", str);
    }
    
    Output:
    Enter any character
    D
    Entered character is D
    Enter any string ( upto 100 character )
    Durgesh Kumar Tiwari
    Entered string is Durgesh
    

    The format specifier %d is used in scanf() statement. So that, the value entered is received as an integer and %s for string.

    Ampersand is used before variable name ?ch? in scanf() statement as &ch.

  • Key Points to remember in C PRINTF() AND SCANF():

    • printf() is used to display the output and scanf() is used to read the inputs.

    • printf() and scanf() functions are declared in ??stdio.h?? header file in C library.

    • All syntax in C language including printf() and scanf() functions are case sensitive.

What next?

The next topic is C Data Types

Share this page