These are the notes for C episode 4. Until now every number lived inside the code. Here the user types it in with scanf. You will learn why printf alone can't take input, how scanf("%d", &bill) works, why forgetting & crashes the program, how to read several values at once, which format specifier to use for each type (and why double needs %lf), the leftover-Enter trap with %c, and what scanf returns. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run with the input shown.
Why
-Wno-unused-result? On Ubuntu, gcc adds an extra warningignoring return value of 'scanf' declared with attribute 'warn_unused_result'every time you callscanfwithout using its result. The flag hides that noise so the important warnings stand out. (By the end of these notes you will know how to use the result properly.)
The problem: the bill stuck in the code
The chaat bhaiya loved our bill splitter from episode 3 and wants to use it at his stall every day. But every table has a new bill: ₹250, then ₹340, then ₹180. In our program the bill is written inside the code:
#include <stdio.h>
int main() {
int bill = 250;
printf("Each pays: %d\n", bill / 4);
return 0;
}
Output:
Each pays: 62
For every new bill he would have to open the code, change the number, compile and run again. He doesn't know C. The program has to ask him. The obvious attempt:
#include <stdio.h>
int main() {
int bill;
printf("Enter the bill: ");
printf("Each pays: %d\n", bill / 4);
return 0;
}
Output:
Enter the bill: Each pays: 0
It never waited. And that 0 isn't a real answer: bill was never given a value, so it holds whatever junk was in memory. Here it happened to be zero.
Why? printf only talks. It puts text on the screen, and that's all it can do. "Enter the bill" is a question with nobody listening for the answer. We need the opposite of printf: something that waits for the keyboard, listens, and puts what you typed into bill.
The fix: scanf listens
Think of a waiter. When he reads out the menu, he talks and you listen: that's printf. When he takes your order, you talk and he listens and writes it down: that's scanf (scan formatted input). To write the order he needs two things: what kind of thing it is (a number of plates) and where to write it (slip number 7).
scanf("%d", &bill);
// ^^ ^^^^^
// | where to put it: the address of bill
// what kind: a whole number
#include <stdio.h>
int main() {
int bill;
printf("Enter the bill: ");
scanf("%d", &bill);
printf("Each pays: %d\n", bill / 4);
return 0;
}
Input:
340
Output:
Enter the bill: Each pays: 85
The program asked, scanf listened, and bill became 340. The bhaiya can now type any bill without touching the code.
On SyntaxPilot (and other online compilers) you type the input in the input box before you run, and the typed
340does not appear in the output. In a real terminal the program stops and waits, and you seeEnter the bill: 340with your typing next to the question.
The & sign and the crash
The most common beginner mistake in all of C: typing fast and forgetting the &.
#include <stdio.h>
int main() {
int bill;
printf("Enter the bill: ");
scanf("%d", bill);
printf("Bill is %d\n", bill);
return 0;
}
gcc warns:
main.c:6:13: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=]
6 | scanf("%d", bill);
| ~^ ~~~~
| | |
| | int
| int *
Then, with input 250, the program crashes:
Segmentation fault
(Your terminal may add (core dumped); the exit code is 139.) It never even printed the bill. (Because bill holds junk, the exact behaviour is undefined: usually a crash, sometimes worse, silent memory corruption.)
Why scanf needs &: an address, not a name
A delivery labelled "Deliver to Ravi" is useless: which Ravi? where? A label saying "House 42" takes the delivery person straight to the door.
| Delivery | C | What scanf gets |
|---|---|---|
| "Deliver to Ravi" | bill |
the value inside bill (junk) |
| "Deliver to House 42" | &bill |
the address of bill's box in memory |
| Parcel left at the door | bill is now 340 |
scanf wrote into that address |
&means "the address of".&billis wherebilllives in memory.- Without
&, scanf got the junk value insidebill, treated it as a memory address, tried to write there, and crashed. printfonly needs the value to show it;scanfneeds the address to change it.- The
int *in the warning means "the address of an int" (a pointer to int).
You can print an address with %p (for pointer):
#include <stdio.h>
int main() {
int bill = 250;
printf("bill holds: %d\n", bill);
printf("bill lives at: %p\n", &bill);
return 0;
}
Output (one run):
bill holds: 250
bill lives at: 0x7ffd05b48574
That hexadecimal number is bill's house number in memory. You'll get a different one every run, and that's fine. Addresses are a big topic called pointers, covered later in the course. For now, one rule: in scanf, numbers and characters need an &.
Reading two values at once
Tables aren't always four friends. One scanf can read the bill and the number of friends: write %d twice and give two addresses.
#include <stdio.h>
int main() {
int bill, friends;
printf("Bill and friends: ");
scanf("%d %d", &bill, &friends);
printf("Each pays: %.2f\n", (float)bill / friends);
return 0;
}
Input (space between):
250 4
Input (on two lines):
250
4
Output for both:
Bill and friends: Each pays: 62.50
For numbers, scanf skips over spaces, tabs and Enters until it finds the next value. (The (float) cast from episode 3 keeps the paise.)
Format specifiers must match the type
Bills have paise: ₹250.50. We change bill to a float but forget to change the %d:
#include <stdio.h>
int main() {
float bill;
printf("Enter the bill: ");
scanf("%d", &bill);
printf("Bill is %.2f\n", bill);
return 0;
}
Input 250.50. gcc warns:
main.c:6:13: warning: format '%d' expects argument of type 'int *', but argument 2 has type 'float *' [-Wformat=]
Output:
Enter the bill: Bill is 0.00
The specifier is a form that tells scanf what shape of data to expect. If the form says "whole number" but the box is a decimal box, the data lands wrong. Change %d to %f:
scanf("%f", &bill);
Output:
Enter the bill: Bill is 250.50
The double trap: %lf in scanf
In printf, %f works for double. In scanf, a double needs %lf:
#include <stdio.h>
int main() {
double price;
scanf("%f", &price);
printf("Price: %.2f\n", price);
return 0;
}
Input 99.50. gcc warns (and suggests %lf underneath):
main.c:5:13: warning: format '%f' expects argument of type 'float *', but argument 2 has type 'double *' [-Wformat=]
Output:
Price: 0.00
Fix: scanf("%lf", &price); and the output is:
Price: 99.50
Why the difference? printf receives values, and a float value is automatically promoted to double, so %f covers both. scanf receives addresses, and it must know whether the box at that address is 4 bytes (float) or 8 bytes (double).
scanf format specifiers
| Specifier | Type | Example |
|---|---|---|
%d |
int |
scanf("%d", &plates); |
%f |
float |
scanf("%f", &bill); |
%lf |
double |
scanf("%lf", &price); (not %f!) |
%c |
char |
scanf(" %c", &size); (note the space) |
%lld |
long long |
scanf("%lld", &views); |
Two rules: the type and the specifier must match (when they don't, gcc tells you, so read the warnings), and every variable gets its &.
The leftover Enter key: the %c trap
The bhaiya also wants the order: how many plates, and the size S, M or L. So we read a number, then a character. When you type 3 and press Enter, two characters go in: '3' and the Enter key itself, '\n'.
| At the token counter | In C |
|---|---|
| You type 3, then press Enter | the input queue holds 3\n |
%d takes the 3, the Enter stays in the tray |
scanf("%d") leaves \n behind |
%c grabs whatever is first, the Enter! |
scanf("%c") gives size = '\n' |
#include <stdio.h>
int main() {
int plates;
char size;
printf("Plates: ");
scanf("%d", &plates);
printf("Size (S/M/L): ");
scanf("%c", &size);
printf("\nOrder: %d plates, size [%c]\n", plates, size);
return 0;
}
Input:
3
L
Output:
Plates: Size (S/M/L):
Order: 3 plates, size [
]
The brackets are broken across two lines: size got the Enter key, not the L. No warning, no error.
The fix is one space before %c. A space in a scanf format means "skip any spaces, tabs and Enters first":
scanf(" %c", &size);
Output:
Plates: Size (S/M/L):
Order: 3 plates, size [L]
Rule: always write " %c" when reading a character after a number (or after any earlier input).
What scanf returns
A customer grabs the keyboard and types the bill in words: two fifty. %d expects digits, sees a t, gives up, and bill stays untouched. But scanf doesn't fail silently: it returns how many values it managed to read.
#include <stdio.h>
int main() {
int bill = 0;
printf("Enter the bill: ");
int got = scanf("%d", &bill);
printf("\nValues read: %d, bill: %d\n", got, bill);
return 0;
}
Input two fifty:
Enter the bill:
Values read: 0, bill: 0
Input 250:
Enter the bill:
Values read: 1, bill: 250
bill is still 0, the value we started with, when nothing could be read. Some extra cases (verified):
| Code | Input | scanf returns |
|---|---|---|
scanf("%d", &a) |
250 |
1 |
scanf("%d", &a) |
two fifty |
0 (nothing matched) |
scanf("%d %d", &a, &b) |
12 abc |
1 (only a was read; b untouched) |
scanf("%d", &a) |
(no input at all) | -1, which is EOF |
A good program checks this number, and if it's 0 says "please type a number". Making that decision needs if and else: the next episode.
Common mistakes (and the real gcc messages)
| Mistake | Code | What gcc says / what happens |
|---|---|---|
Forgetting & |
scanf("%d", bill); |
warning: format '%d' expects argument of type 'int *', but argument 2 has type 'int' [-Wformat=], then Segmentation fault |
| Specifier doesn't match the type | float bill; scanf("%d", &bill); |
warning: format '%d' expects argument of type 'int *', but argument 2 has type 'float *' [-Wformat=], prints 0.00 |
%f for a double in scanf |
double p; scanf("%f", &p); |
warning: format '%f' expects argument of type 'float *', but argument 2 has type 'double *' [-Wformat=], prints 0.00 |
%c right after a number |
scanf("%c", &size); |
no error; size is the Enter key. Fix: scanf(" %c", &size); |
| Using the variable before input | int bill; printf("%d", bill / 4); |
no error; junk value |
| Ignoring the return value | scanf("%d", &bill); with input two fifty |
no error; bill keeps its old (maybe junk) value |
gcc's warnings name the exact problem, so read them.
Mini project: chaat stall bill splitter
#include <stdio.h>
int main() {
int bill, tip, friends;
printf("Bill: ");
scanf("%d", &bill);
printf("Tip %%: ");
scanf("%d", &tip);
printf("Friends: ");
scanf("%d", &friends);
float total = bill + bill * tip / 100.0;
printf("\nTotal: %.2f\n", total);
printf("Each pays: %.2f\n", total / friends);
return 0;
}
Input:
340
10
4
Output:
Bill: Tip %: Friends:
Total: 374.00
Each pays: 93.50
%%in printf prints a single%sign.100.0(not100) avoids integer division, as in episode 3.- For the next table he just types new numbers. No code changes ever again.
Practice
- Read your age and print the year you turn 60 (assume the current year is 2026).
- Read a length in centimetres and print it in metres (use
float). - Read marks (a number) and then a grade letter, using
" %c". - Read two numbers and print their sum, difference and average.
- What does
scanf("%d %d", &a, &b)return if the user types12 abc? What areaandbif both started at 0?
Solutions and hints
1. Read the age and add the years left until 60. Input 20 prints You turn 60 in 2066.
int age;
scanf("%d", &age);
printf("You turn 60 in %d\n", 2026 + (60 - age));
2. Use a float and divide by 100. Input 172 prints 1.72 m.
float cm;
scanf("%f", &cm);
printf("%.2f m\n", cm / 100);
3. Input 87, Enter, A prints Marks 87, grade A. Without the space before %c, grade would be the Enter key.
int marks;
char grade;
scanf("%d", &marks);
scanf(" %c", &grade);
printf("Marks %d, grade %c\n", marks, grade);
4. Input 7 4 prints Sum 11, difference 3, average 5.50. Divide by 2.0, not 2, or 5.5 becomes 5.
int a, b;
scanf("%d %d", &a, &b);
printf("Sum %d, difference %d, average %.2f\n", a + b, a - b, (a + b) / 2.0);
5. It returns 1: a is 12, and b stays 0 because abc is not a number.
Quick quiz
The user types 5, presses Enter, presses Enter again on an empty line, then types 7. What does this print?
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", a + b);
- A.
57 - B.
12 - C.
5 - D. Error
Answer
B: 12. For %d, scanf skips every space, tab and Enter before a number, even an empty line. So a is 5, b is 7, and the sum is 12. (Verified with input 5\n\n7: the program prints 12.)
Interview questions
- What is the difference between
printfandscanf? - Why does
scanfneed&butprintfdoesn't? - What happens if you forget
&inscanf? What is a segmentation fault? - Why is
%lfrequired fordoubleinscanfbut%fworks inprintf? - Why does
scanf("%c", &ch)after reading a number give a newline, and how do you fix it? - What does
scanfreturn? What does a return value of0orEOFmean? - Why don't you use
&when reading a string into achararray with%s? (Preview: an array name already acts as an address.)
Summary
printftalks,scanflistens:scanf("%d", &bill)says what kind of value and where to put it.&billis the address ofbill. Forget the&and the program usually crashes with a segmentation fault.- One
scanfcan read many values:"%d %d", with an&for each. Spaces and Enters are skipped for numbers. - Match the specifier to the type:
%dint,%ffloat,%lfdouble,%cchar. - Write
" %c"(with a space) to skip the leftover Enter key. scanfreturns how many values it read;0means the input didn't match.
Next episode: if, else and switch. Today scanf told us when the input was bad, but our program just carried on. Next time, when scanf reads 0 values, the program will say "please type a number".