Getting Input From Users

Lesson 12
Author : Afrixi
Last Updated : January, 2023
C - Programming Language
This course covers the basics of programming in C.

In C, we can read input from the user using the scanf() function. The scanf() function reads formatted input from the standard input (usually the keyboard) and stores the values in the specified variables.

The basic syntax for the scanf() function is:

scanf("format_string", &variable1, &variable2, ...);

Here, format_string is a string that specifies the format of the input expected, and &variable1, &variable2, etc. are pointers to the variables where the input values will be stored.

For example, to read an integer value from the user, we can write:

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

In this example, we prompt the user to enter an integer, and then use the scanf() function with the format string %d to read the integer value entered by the user and store it in the variable num.

We can also read multiple input values using a single scanf() function call. For example, to read two integer values, we can write:

int num1, num2;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);

In this example, we prompt the user to enter two integers, and then use the scanf() function with the format string %d %d to read the two integer values entered by the user and store them in the variables num1 and num2.

Here’s an example code that reads two integer values from the user and prints their sum:

#include <stdio.h>

int main() {
    int num1, num2;

    printf("Enter two integers: ");
    scanf("%d %d", &num1, &num2);

    int sum = num1 + num2;

    printf("The sum of %d and %d is %d\n", num1, num2, sum);

    return 0;
}

In this example, we read two integer values entered by the user using the scanf() function, store them in the variables num1 and num2, and then calculate their sum and print it to the console.