Input and Output in C

1. What is printf()?

printf() is used to display (print) output on the screen. It's a standard output function provided by the C Standard Library.

Example:

#include <stdio.h>

int main() {
    printf("Hello, World!");
    return 0;
}

Output: Hello, World!

2. What is scanf()?

scanf() is used to take input from the user. It stores the value entered by the user in the variable.

Example:

#include <stdio.h>

int main() {
    int age;
    printf("Enter your age: ");
    scanf("%d", &age);  // &age stores the input in the variable age
    printf("You are %d years old.", age);
    return 0;
}

Input: 21
Output: You are 21 years old.

3. Format Specifiers

Format specifiers tell the compiler the type of data:

4. Example Using Multiple Inputs

#include <stdio.h>

int main() {
    int roll;
    float marks;
    char grade;

    printf("Enter Roll Number: ");
    scanf("%d", &roll);

    printf("Enter Marks: ");
    scanf("%f", &marks);

    printf("Enter Grade: ");
    scanf(" %c", &grade); // Note the space before %c

    printf("Roll: %d\nMarks: %.2f\nGrade: %c", roll, marks, grade);
    return 0;
}

5. Why Use & in scanf()?

The & (address-of) operator gives the memory address of the variable so that scanf() can store the input value there.