C User Input

In C, you can take input from the user using the scanf() function. Here's an example code snippet that takes an integer input from the user and prints it on the console:


 
#include <stdio.h>

int main() {
    int num;

    printf("Enter an integer: ");
    scanf("%d", &num);

    printf("You entered: %d", num);

    return 0;
}

Let's go over this code line by line:

  • We first include the standard input/output library stdio.h.
  • In the main() function, we declare an integer variable called num.
  • We then print a message asking the user to enter an integer using the printf() function.
  • We use the scanf() function to read the integer input from the user and store it in the num variable. The & operator is used to get the address of the variable num.
  • Finally, we print the entered value of num using the printf() function.

You can use similar logic to take input of other data types like float, double, char, string, etc.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

66436