Mastering Input with the scanf() Pre-defined Function in C

24 Feb 2023 Balmiki Mandal 0 C Programming

A Comprehensive Guide to Using the scanf() Function in C Programming

In C programming, scanf() is a built-in function that is used to read input from the console or terminal. It stands for "scan formatted" and allows the programmer to read text, numbers, and other values from the user in a variety of formats.

Basic syntax of the scanf() function.

scanf("format string", &variable1, &variable2, ...);
  • "format string" is a string that contains the format of the input to be read. It can include placeholders for the types of variables to be read.
  • &variable1, &variable2, etc. are the addresses of the variables where the input values will be stored.

The format string can include special characters and escape sequences to control the formatting of the input. For example, the %d placeholder is used to read an integer value, %f is used to read a floating-point value, and %s is used to read a string.

Here is an example of using the scanf() function to read two integer values from the user:

int x, y; printf("Enter two integer values: ");
scanf("%d %d", &x, &y);
printf("You entered %d and %d\n", x, y);

In this example, the format string "%d %d" includes two %d placeholders, which tell the scanf() function to read two integer values separated by a space. The &x and &y variables are the addresses of the variables where the input values will be stored.

When this code is executed, it will prompt the user to enter two integer values, separated by a space. Once the user enters the values and presses Enter, the scanf() function will read the values and store them in the x and y variables. The second printf() statement then displays the entered values on the console.

The scanf() function is a useful tool for reading input from the user in C programming and can be used to create interactive programs that respond to user input

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.