The scanf Function in C

The scanf Function in C

The scanf Function in C

The scanf function in C is used to take input from the user. It reads data from standard input (usually the keyboard) and stores it in the provided variables. This function is essential for interactive programs where user input is needed.

What Does scanf Do?

The scanf function reads formatted input. It uses placeholders similar to printf to specify the type of data it expects, such as %d for integers, %f for floating-point numbers, and %s for strings.

Example of scanf in Action

Here’s a simple example:

#include <stdio.h>

int main() {
    int number;
    printf("Enter an integer: ");
    scanf("%d", &number);
    printf("You entered: %d\n", number);
    return 0;
}

In this example, the program prompts the user to enter an integer. The scanf function reads the input and stores it in the number variable.

Example Output:
Enter an integer: 42
You entered: 42

The scanf function is a powerful tool in C for gathering user input, allowing your programs to be more dynamic and interactive.

Comments

Popular Posts