C printf and scanf

printf() prints output on the screen and scanf() reads input from the keyboard. Both are defined in the stdio.h header file.

printf()

#include <stdio.h>

int main(void) {
    int age = 21;
    float marks = 86.5f;
    char grade = 'A';

    printf("Welcome to C\n");
    printf("Age: %d, Marks: %.1f, Grade: %c\n", age, marks, grade);
    return 0;
}

Output:

Output of the above program is

Welcome to C
Age: 21, Marks: 86.5, Grade: A

scanf()

scanf() needs the address of the variable, so we write & before its name. Here the user types 20 and 30.

#include <stdio.h>

int main(void) {
    int a, b;

    printf("Enter two numbers: ");
    scanf("%d %d", &a, &b);
    printf("Sum = %d\n", a + b);
    return 0;
}

Output:

Output of the above program is

Enter two numbers: 20 30
Sum = 50

Reading different types

#include <stdio.h>

int main(void) {
    int age;
    float height;
    char initial;

    scanf("%d %f %c", &age, &height, &initial);
    printf("%d, %.2f, %c\n", age, height, initial);
    return 0;
}

Output:

Output of the above program is

19, 5.70, R

Common mistakes

  • Forgetting & in scanf("%d", &n). This crashes the program.
  • Using a wrong format specifier, like %d for a float.
  • scanf("%s") stops at the first space, so it cannot read a full name with spaces.
Note: The format specifiers are explained in C Format Specifiers.

Next: C Escape Sequences.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a C program to swap the values of two variables using a third variable
Write a C program to print words using spacing and new line characters
Write a C program to get the salary from the user and print it
Write a C program to find the size of int, float, long, double and char
Write a C program to get the marks of 5 subjects and find the total and average
Write a C program to calculate the perimeter of a rectangle
Write a C program to convert minutes into hours and minutes
Interview Questions & Answers
What is the difference between a variable and a constant in C?
What are the data types in C?
What is the difference between = and == in C?
What is the difference between ++i and i++ in C?
What is the use of the sizeof operator in C?
How to swap two numbers in C?