C – Read Integer using Scanf()

To read an integer entered by user via standard input in C language, use scanf() function.

scanf() reads input from stdin(standard input), according to the given format and stores the data in the given arguments.

So, to read an integer from console, give the format and argument to scanf() function as shown in the following code snippet.

int n;
scanf("%i", n);

Here, %i is the format to read an int value and this integer is stored in variable n.

Examples

In the following example, we read an integer input by the user in standard input to a variable n using scanf() function.

main.c

#include <stdio.h>

int main() {
    int n;
    printf("Enter an integer : ");
    //read input from user to "n"
    scanf("%i", &n);
    //print to console
    printf("You entered %i!\n", n);
    return 0;
}

Output

Enter an integer : 25
You entered 25!
Program ended with exit code: 0
Enter an integer : -67
You entered -67!
Program ended with exit code: 0
ADVERTISEMENT

Conclusion

In this C Tutorial, we learned how to read an integer entered by user via standard input using scanf() function.