C Program to Take Input from the User

In this article, we will write a C program to take input from the user.

The program takes an integer input from the user and prints it on the output screen.

Sample Input:

Enter any number: 100

Output:

The number you have entered is 100

In C programming, there are different ways to take input from the user. However, the most commonly used approach is to use the scanf() function.

The scanf() function is a part of the standard input/output library. It takes the formatted input from the user or from a file. It is generally used to take non-string inputs from the user such as int, float, double, etc.

The following C program shows how you can take input from the user using the scanf() function:

// C program to take input from the user
#include <stdio.h>

int main() {
    
    // Declare the variable 
    int num;

    // Print message on the screen
    printf("Enter any number: ");

    // Take input from the user
    scanf("%d", &num);

    // Print the entered number
    printf("You have entered %d", num);

    return 0;

}

Output:

Enter any number: 100
The number you have entered is 100

Example 2: Take Multiple Inputs from the User

You can also take multiple inputs from the user using the scanf() function.

Here is the syntax to take multiple inputs from the user using the scanf() function:

scanf("%[format specifier]", &variable1, &variable2, ...);

In the following C program, we have declared two integer variables num1 and num2 and used the scanf() function to take their values from the user.

The first value entered by the user is stored in the num1 variable and the second value is stored in the num2 variable i.e. the first %d refers to num1 and second %d refers to num2.

// C program to take multiple inputs from the user
#include <stdio.h>

int main() {

    // Declare the variables
    int num1, num2;

    // Print message on the screen
    printf("Enter Two numbers: ");

    // Take inputs from the user
    scanf("%d %d", &num1, &num2);

    // Print the entered numbers
    printf("The numbers you have entered are %d and %d", num1, num2);

    return 0;

}

Output:

Enter Two numbers: 10 20
The numbers you have entered are 10 and 20

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts