scanf function in c – printf and scanf function in C Programming

scanf function in c: The printf and scanf functions are the most popular input and output functions in C language. Both functions are inbuilt library functions which is part of stdio.h header file. Before using both functions in our program, we must include stdio.h header file as shown below.

#include <stdio.h>

printf Function in C

The printf function of stdio C Library writes a formatted string to stdout. If format contains format specifiers (subsequences beginning with %), the additional arguments following format are inserted after formatting in the resulting string by replacing their respective format specifiers.

Syntax of printf function
int printf(const char *format, …);

C program to print formatted strings using printf

The following program shows the use of printf function to print a formatted literals on screen.

printf and scanf function in C Programming

#include <stdio.h>
 
int main(){
 
    printf("Printing characters\n");
    printf("%c %c %c %c\n\n", 'a', 'A', '#', '1');
     
    printf("Printing integers\n");
    printf("%d %ld %10d %010d\n\n", 2015, 2015L, 2015, 2015);
     
    printf("Printing floating point numbers\n");
    printf("%f %5.2f %+.0e %E\n\n", 1.41412, 1.41412, 1.41412, 1.41412);
     
    printf("Printing string\n");
    printf("%s\n\n", "TechCrashCourse");
     
    printf("Printing radicals\n");
    printf ("%d %x %o %#x %#o\n\n", 2105, 2015, 2015, 2015, 2015);
     
    return 0;
}

Output

Printing characters
a A # 1

Printing integers
2015 2015       2015 0000002015

Printing floating point numbers
1.414120  1.41 +1e+000 1.414120E+000

Printing string
TechCrashCourse

Printing radicals
2105 7df 3737 0x7df 03737

scanf Function in C

The scanf function of stdio C Library function reads formatted data from stdin and stores them in the variables pointed by the additional arguments. Additional arguments must point to variables of the same type as specified in the format.

Format is a null terminated string that contains Whitespace character, Non-whitespace character and Format specifiers.

Syntax of scanf function
int scanf(const char *format, …);

C program to take input from user using scanf function

The following program shows the use of scanf function to read formatted data from a stdin.

C program to take input from user using scanf function

#include <stdio.h>
 
int main(){
    int a, b, sum;
    printf("Enter to integers to add\n");
    /* Taking input from user using scanf */
    scanf("%d %d", &a, &b);
    sum = a + b;
     
    printf("%d + %d = %d", a, b, sum);
 
    return 0;
}

Output

Enter to integers to add
3 9
3 + 9 = 12