MARCO PAOLO RODRIGUEZ TALAMANTES
4 months ago
Marcocountry asked

How do I scan user input?

Kelish Rai
Expert
3 months ago
Kelish Rai answered

In C, you can take user input using the scanf() function. It reads values entered by the user and stores them in variables. For example,

#include 

int main() {
    int number;
    
    printf("Enter a number: ");

    // Take input and store it in number variable
    scanf("%d", &number);

    printf("You entered: %d\n", number);
    
    return 0;
}

Output

Enter a number: 42
You entered: 42

Here,

  1. printf() asks the user to enter a number.

  2. scanf("%d", &number); takes the user's input and stores it in the number variable.

    • %d tells scanf that you're expecting an integer.

    • &number is the address of the variable where the input will be stored.

  3. Finally, printf() displays the entered number.

Note: Always remember to use & (address-of operator) before the variable name in scanf().

C
This question was asked as part of the Practice: C Programming course.