The scanf() function in C – Accepting userinput in C

Filed Under: C Programming
C Scanf() Function

Hey, all. In this article, we will be focusing on the scanf() function in C in detail.


Working of the scanf() function in C

Be it any programming language, we always need user input, in order to make it work with a dynamic set of values.

This is where the scanf() function in C comes into picture.

The scanf() function enables the programmer to accept formatted inputs to the application or production code. Moreover, by using this function, the users can provide dynamic input values to the application.

Having understood the working of scanf() function, let us now focus on the structure of the same.


Syntax of scanf() function

Let us have a look at the below syntax:

scanf("%format-specifier", &variable)
  • format_specifier: It decides the type of value to be taken as input from the standard input device. Example: “%d” for integer, “%c” for character values, etc.
  • variable: The value taken as input from the user gets stored at the location pointed by the variable.

The scanf() function accepts the value of the specified type through the help of the format specifiers and stores the value at the location pointed by the variable passed as a parameter to it.

Let us now implement the scanf() function through the below examples.


Examples of scanf() function

In the below example, we have accepted the integer value as input and have displayed the value.

#include <stdio.h> 
int main() 
{ 
	int x; 
	scanf("%d", &x); 
	printf("The value of x is: %d", x); 
	return 0; 
} 

Output:

20
The value of x is: 20

Now, we have accepted the string values as input and displayed the same.

#include <stdio.h>

int main () {
   char city[20];

   printf("Enter name of the city: ");
   scanf("%s", city);
   printf("The city value is: %s", city);
   
   return(0);
}

Output:

Enter name of the city: Pune
The city value is: Pune

Conclusion

By this, we have come to the end of this topic. The scanf() function can be used to accept values of different data types, thus making it a user-friendly function.

Feel free to comment below in case, you come across any question.

For more such posts related to C programming, do visit C programming with us.

Till then, Happy Learning!!


References

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages