Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
scanf Syntax
3.
Example Format Specifiers Recognized by scanf
4.
Return Value of scanf
5.
Why & is important?
6.
Example of scanf
6.1.
C
7.
Frequently Asked Questions
7.1.
What happens if I use the wrong format specifier in scanf?
7.2.
Can scanf read more than one input at a time?
7.3.
Why do I sometimes need to put a space before %c in scanf?
8.
Conclusion
Last Updated: Apr 3, 2024
Easy

Scanf In C

Author Sinki Kumari
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

Introduction

In C programming, there is a very important function which interacts with user straightforwardly, it’s scanf function, a simple yet powerful tool for reading formatted input from the standard input stream, typically the keyboard. This function enables a program to accept user input in a structured and controlled manner, making it an indispensable part of creating interactive applications.

Scanf In C

In this article, we'll learn about its syntax, the variety of format specifiers it supports, its return values, and the crucial role of the '&' operator.

scanf Syntax

To make a program do something useful, like solving a problem or performing a task, we often need to talk to it, tell it what we want by typing in some data. That's where scanf comes into play in C programming. It's like asking for specific details: "What's your name?" or "How old are you?". In coding terms, scanf allows your program to ask for these details.

The way you write scanf in your code is pretty straightforward. You start with the word scanf, followed by parentheses (). Inside these parentheses, you first put what kind of information you're asking for, wrapped in quotes "", and then you tell the program where to store this information.

Here's a simple way to look at it:

scanf("format specifier", &variable);

 

  • "format specifier" tells the program what kind of data you're expecting, like a number or a letter.
     
  • &variable is the place in the program where you want to keep the data that the user gives.
     

It's crucial to match the right format specifier with the kind of data you're asking for, or else the program might get confused and not work right. 

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Example Format Specifiers Recognized by scanf

When we use scanf in our programs, it's like filling in a form where each blank space has a specific type of information it needs. In programming with C, these "blank spaces" are defined by what we call format specifiers. They tell scanf what type of data we're expecting from the user. Think of it as labeling jars in the kitchen for sugar, salt, and spices; each jar should contain the right ingredient. Here are some common "labels" (format specifiers) that scanf uses:

  • %d for whole numbers (integers). Example: 5, -3, 42.
     
  • %f for floating-point numbers (decimals). Example: 3.14, -0.001, 2.718.
     
  • %c for single characters. Example: 'a', 'Z', '3'.
     
  • %s for strings (a sequence of characters). Example: "hello", "1234".
     

When you write scanf, you choose the right specifier for the data you want. For instance, if you want an age, you use %d because age is a whole number. If you're going to get the first letter of someone's name, you use %c because it's a single character.

Here's an example:

int age;
char firstLetterOfName;
scanf("%d", &age); // For an integer
scanf("%c", &firstLetterOfName); // For a character

In these lines, the first scanf expects an integer value from the user and stores it in the variable age. The second scanf awaits a single character and saves it in firstLetterOfName.

Return Value of scanf

Every time you use scanf in a C program, it's not just about getting input. scanf also tells you something back. It gives you a number that shows how many items it successfully read. This is what we call the return value of scanf.

Imagine you ask for two things: a number and a letter. If you get both correctly, scanf returns 2, meaning "I got 2 pieces of information as asked." If you only get the number right, scanf might return 1, saying "I only got 1 out of 2 right."

Here's how you can see this in a program:

int number;
char letter;
int result = scanf("%d %c", &number, &letter);


In this example, result will store the return value of scanf. If the user enters a number and a letter correctly, result will be 2. If something goes wrong, like the user doesn't enter the right type of data, result might be 1 or even 0, indicating how many items were successfully read.

Why & is important?

In C programming, when we use scanf, we often see an & before the variable name. This & is not just a random symbol; it has a very important job. It tells scanf where the piece of data should be stored in the computer's memory.

Think of it this way: your program has many boxes where it can keep data, and each box has a label. The & symbol helps scanf understand which box (or variable) you want to use to store the input data. Without &, scanf wouldn't know where to put the information it gets.

Here's a simple example:

int age;
scanf("%d", &age);


In this code, age is a box where you want to store a number. The %d tells scanf you're expecting an integer. The & before age helps scanf understand that it should put the number it gets into the age box.

The & is crucial because it ensures that the data goes to the right place. If you forget it, scanf won't work as expected, and your program might not behave correctly.

Example of scanf

Let's put everything we've talked about into practice with a simple example. We'll write a small program that asks for a user's age and their favorite letter of the alphabet, then prints these details back to the screen.

Here's the code:

  • C

C

#include <stdio.h>

int main() {
int userAge;
char favoriteLetter;

printf("Enter your age: ");
scanf("%d", &userAge);

// To read a single character after an integer input, we need to include a space before %c in the format string.
// This is because scanf leaves the newline character in the buffer after reading the integer,
// and we need to consume it before reading the next character.
printf("Enter your favorite letter: ");
scanf(" %c", &favoriteLetter);

printf("You are %d years old and your favorite letter is %c.\n", userAge, favoriteLetter);

return 0;
}

Output

Enter your age: 27
Enter your favorite letter: G R
You are 27 years old and your favorite letter is R.


In this program:

  • We first declare two variables, userAge for storing the age and favoriteLetter for storing the letter.
     
  • We then use printf to ask the user for their age and use scanf("%d", &userAge) to read and store the age. %d tells scanf we want an integer, and &userAge points to where to store it.
     
  • Next, we ask for the favorite letter. Notice the space before %c in scanf(" %c", &favoriteLetter). This space is essential because it tells scanf to skip any whitespace characters (like the newline character left from entering the age) before reading the next character.
     
  • Finally, we use printf to show the entered age and favorite letter.

Frequently Asked Questions

What happens if I use the wrong format specifier in scanf?

Using the wrong format specifier can lead to unexpected results. For example, if you use %d (for integers) when you should use %f (for floating-point numbers), scanf might not read the input correctly, and your program could behave unpredictably.

Can scanf read more than one input at a time?

Yes, scanf can read multiple inputs in one go. You just need to provide the right format specifiers and variables. For instance, scanf("%d %c", &age, &letter) can read an integer and a character sequentially from the same line of input.

Why do I sometimes need to put a space before %c in scanf?

The space before %c tells scanf to ignore any whitespace characters (like spaces or newline characters) before reading the next non-whitespace character. This is often needed after reading a different type of input, like an integer, to avoid having scanf read the leftover newline character as the character input.

Conclusion

In this article, we learned everything about the scanf function in C, starting with its basic syntax and then we talked about the various format specifiers it supports. We've also discussed its return value, which gives us an idea  into how many inputs were successfully read, and highlighted the significance of the & operator in directing input to the right memory locations. 

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass