โจ๏ธ 5. Input & Output in C
A program becomes interactive when it can receive information from the user and display useful results.
The examples here use the standard input/output library declared through <stdio.h>.
Variables hold data. Input brings data into a program, and output sends results to a user, file, or another destination.
A common pattern is to read data, process it, and display a result. The diagram below shows that pattern.
5.1 What Is Input and Output?
Input
Input is information supplied to a program.
Examples:
- Age entered by a user
- Two numbers used in a calculation
- A character entered from the keyboard
- A name entered by the user
Output
Output is information produced by a program.
Examples:
- A calculated total
- A message displayed on the screen
- The result of a comparison
- A formatted report
Basic Program Communication
User | | Input v +----------------+ | C Program | | | | Read -> Process| | -> Result | +----------------+ | | Output v Screen
5.2 Standard Input/Output and <stdio.h>
C provides many standard input/output functions through the header file:
#include <stdio.h>
The name stdio comes from standard input/output
Functions such as
printf(),
scanf(),
getchar(),
putchar(),
fgets(),
and
puts()
are declared by the standard I/O facilities provided through
<stdio.h>.
Basic console I/O functions
| Function | Purpose |
|---|---|
printf() |
Formatted output |
scanf() |
Formatted input |
getchar() |
Read one character |
putchar() |
Write one character |
fgets() |
Read a line of text |
puts() |
Write a string followed by a newline |
5.3 printf() โ Displaying Output
The printf() function is used to produce
formatted output on the standard output stream.
Basic syntax
printf("format string", values);
Simple example
#include <stdio.h>
int main(void)
{
printf("Hello, CodeBhavya!");
return 0;
}
The text inside quotation marks is called a string literal
Printing multiple pieces of information
#include <stdio.h>
int main(void)
{
int age = 20;
printf("Age = %d", age);
return 0;
}
Here, %d tells printf()
how the corresponding value should be formatted.
5.4 Format Strings and Format Specifiers
A format string contains ordinary text and special conversion specifications.
printf("Age = %d", age);
|
+---- %d = format specifier
| Specifier | Common printf() use |
|---|---|
%d |
Signed int |
%i |
Signed int |
%u |
Unsigned int |
%ld |
long |
%lld |
long long |
%f |
double in printf's variadic arguments |
%Lf |
long double |
%c |
Character |
%s |
String |
%zu |
size_t |
The format specifiers used by printf()
and scanf() are not always identical.
The most important beginner example is
%f versus %lf,
which is explained later.
5.5 Printing Integers
int
#include <stdio.h>
int main(void)
{
int number = 125;
printf("Number = %d\n", number);
return 0;
}
unsigned int
#include <stdio.h>
int main(void)
{
unsigned int count = 500;
printf("Count = %u\n", count);
return 0;
}
long
long population = 500000L;
printf("Population = %ld\n", population);
long long
long long distance = 9000000000LL;
printf("Distance = %lld\n", distance);
Choose the format specifier for the argumentโs type, not just for the number you expect to see. For example, an int and a double need different conversions even when both represent 5.
5.6 Printing Floating-Point Values
Floating-point values are commonly represented using
float, double, or
long double.
double with printf()
#include <stdio.h>
int main(void)
{
double price = 149.75;
printf("Price = %f\n", price);
return 0;
}
A float value is automatically promoted to double when passed as a variable argument to the
printf() function, so %f is used
for both ordinary float and double
values in this context.
Printing with two decimal places
double price = 149.7568;
printf("%.2f\n", price);
The output is rounded for the requested display precision:
149.76
5.7 Printing Characters
Use %c when displaying a character.
#include <stdio.h>
int main(void)
{
char grade = 'A';
printf("Grade = %c\n", grade);
return 0;
}
'A' represents a character constant.
"A" is a string literal containing the
character A and a terminating null character.
5.8 Printing Strings
Use %s to print a null-terminated character string.
#include <stdio.h>
int main(void)
{
char name[] = "Bhavya";
printf("Name = %s\n", name);
return 0;
}
char name[] = "Bhavya";
Memory:
+---+---+---+---+---+---+----+
| B | h | a | v | y | a | \0 |
+---+---+---+---+---+---+----+
^
|
null terminator
The \0 character marks the end of a C string.
5.9 Escape Sequences
Escape sequences represent special characters inside character and string literals.
| Escape sequence | Meaning |
|---|---|
\n |
Newline |
\t |
Horizontal tab |
\\ |
Backslash |
\" |
Double quotation mark |
\' |
Single quotation mark |
\r |
Carriage return |
\0 |
Null character |
Newline
printf("Hello\nWorld");
Tab
printf("Name\tMarks\n");
Quotation mark
printf("He said \"Hello\"");
Backslash
printf("C:\\CodeBhavya\\C");
The \0 character is the string terminator.
It is not the same thing as the digit character
'0'.
5.10 Width and Precision Basics
The format string can control how values are displayed.
Precision for floating-point output
double value = 12.34567;
printf("%.2f\n", value);
printf("%.3f\n", value);
printf("%.4f\n", value);
The precision specifies how many digits are displayed after
the decimal point for the f conversion.
Field width
printf("%10d\n", 125);
The value is displayed using a minimum field width of 10 characters.
Combining width and precision
printf("%10.2f\n", 125.456);
You should understand the difference between field width and precision.
5.11 scanf() โ Reading Formatted Input
The scanf() function reads formatted input from
the standard input stream.
Basic syntax
scanf("format", arguments);
Reading an integer
#include <stdio.h>
int main(void)
{
int age;
scanf("%d", &age);
printf("Age = %d\n", age);
return 0;
}
5.12 Why Does scanf() Need &?
For most scalar variables, scanf() needs the
address where it should store the input.
int age;
scanf("%d", &age);
Variable:
age
+-----------+
| ? |
+-----------+
^
|
&age
|
v
scanf() stores the input here
The & operator obtains the address of the variable.
Pointers will explain this mechanism in much greater detail later.
For a character array used as a string, the array expression normally already provides the address of its first element.
char name[20];
scanf("%19s", name);
So &name is not used here.
5.13 scanf() Format Specifiers
| Variable | scanf() conversion | Example |
|---|---|---|
int |
%d |
scanf("%d", &n); |
unsigned int |
%u |
scanf("%u", &n); |
long |
%ld |
scanf("%ld", &n); |
long long |
%lld |
scanf("%lld", &n); |
float |
%f |
scanf("%f", &x); |
double |
%lf |
scanf("%lf", &x); |
long double |
%Lf |
scanf("%Lf", &x); |
char |
%c |
scanf(" %c", &ch); |
| character array | %s |
scanf("%19s", name); |
5.14 The Important %f vs %lf Difference
One of the most common C programming mistakes occurs when reading floating-point values.
For float
float price;
scanf("%f", &price);
For double
double price;
scanf("%lf", &price);
For printf()
float a = 10.5f;
double b = 20.5;
printf("%f\n", a);
printf("%f\n", b);
| Function | float | double |
|---|---|---|
scanf() |
%f |
%lf |
printf() |
%f |
%f |
The difference is about the arguments each function receives. scanf() needs pointers to the exact destination types. Variable arguments passed to printf() follow the default argument promotions, which turn a float value into double. A float pointer does not become a double pointer.
5.15 Reading Multiple Values
Multiple values can be read using one scanf()
statement.
#include <stdio.h>
int main(void)
{
int a, b;
scanf("%d %d", &a, &b);
printf("A = %d\n", a);
printf("B = %d\n", b);
return 0;
}
Input can be supplied as:
10 20
or, because ordinary whitespace separates these conversions:
10
20
For most numeric conversions, whitespace in the input can separate values regardless of whether it is a space, tab, or newline.
5.16 getchar() โ Reading One Character
The getchar() function reads one character from
standard input.
#include <stdio.h>
int main(void)
{
int ch;
ch = getchar();
printf("You entered: %c\n", ch);
return 0;
}
getchar() returns an int so that it can
represent every possible character value as well as the special
value EOF.
5.17 putchar() โ Writing One Character
The putchar() function writes one character to
standard output.
#include <stdio.h>
int main(void)
{
putchar('A');
putchar('\n');
return 0;
}
Using a variable
#include <stdio.h>
int main(void)
{
char grade = 'A';
putchar(grade);
putchar('\n');
return 0;
}
5.18 fgets() โ Reading a Line of Text
The fgets() function is commonly used when a
program needs to read a line of text into a character array.
Basic syntax
fgets(buffer, sizeof buffer, stdin);
Example
#include <stdio.h>
int main(void)
{
char name[50];
printf("Enter your name: ");
fgets(name, sizeof name, stdin);
printf("You entered: %s", name);
return 0;
}
Unlike scanf("%s", ...), it can read spaces and limits how much text fits in the destination array. It reads at most one fewer character than the supplied buffer size and adds a null terminator on success. A newline is retained if it is read.
5.19 puts() โ Writing a String
The puts() function writes a string followed by
a newline.
#include <stdio.h>
int main(void)
{
char message[] = "Welcome to CodeBhavya";
puts(message);
return 0;
}
Compared with printf("%s\n", message),
puts() is a simple option when you only need to
write a string followed by a newline.
5.20 scanf("%s") vs fgets()
| Feature | scanf("%s") | fgets() |
|---|---|---|
| Reads spaces? | No | Yes |
| Can specify maximum field width? | Yes | Yes, through buffer size |
| Simple for one word? | Yes | Also possible, but more than needed |
| Suitable for a complete line? | No | Yes |
| Newline handling | Usually leaves line-ending input unread | May store the newline if it fits |
scanf() with a width limit
char name[20];
scanf("%19s", name);
The width 19 prevents scanf() from
storing more than 19 characters for this conversion, leaving
space for the terminating \0.
The old gets() function is unsafe because it cannot
limit the number of characters read. It was removed from the
C standard in C11.
Use fgets() when reading a line into a character
array.
5.21 Whitespace and scanf()
Different scanf() conversions treat whitespace
differently.
Numeric conversions
Conversions such as %d, %f, and
%lf skip leading whitespace automatically.
Character conversion
The %c conversion does not
skip whitespace automatically.
char ch;
scanf("%c", &ch);
If a newline is already waiting in the input stream, this may read that newline.
Common solution
scanf(" %c", &ch);
The leading space in the format string tells
scanf() to skip whitespace before reading the
character.
The space before %c is part of the format string.
It is not decoration.
5.22 Understanding Leftover Input
Consider:
int age;
scanf("%d", &age);
If the user enters:
20
the numeric conversion reads the 20. The newline
entered after it can remain unread in the input stream.
User enters:
2 0 \n
|---|
|
+---- scanf("%d") consumes 20
The newline may remain:
\n
^
|
unread input
If the next operation is:
char ch;
scanf("%c", &ch);
the character conversion may read that pending newline.
Common approach
scanf(" %c", &ch);
The leading whitespace in the format string skips preceding whitespace before reading the actual character.
Numeric input followed by fgets()
A similar issue can occur when a numeric scanf()
is followed immediately by fgets().
The pending newline may be consumed by fgets(),
making it appear as though the user entered an empty line.
Choose your input method deliberately. Mixing value-by-value
scanf() input with line-based fgets()
means you must handle any unread characters, including newlines. For longer programs, reading each line with fgets and then converting it is often easier to manage.
5.23 Checking the Return Value of scanf()
scanf() returns information about how many input
items were successfully converted and assigned.
Example
#include <stdio.h>
int main(void)
{
int age;
if (scanf("%d", &age) == 1)
{
printf("Age = %d\n", age);
}
else
{
printf("Invalid input\n");
}
return 0;
}
If the input successfully provides one integer,
scanf() returns 1.
The return value of scanf() is the number of
successful assignments. If an input failure occurs before any
conversion is assigned, it can return EOF.
5.24 Standard Streams: stdin, stdout and stderr
C programs commonly interact with three predefined standard streams.
| Stream | Typical purpose |
|---|---|
stdin |
Standard input |
stdout |
Standard output |
stderr |
Standard error output |
Example
#include <stdio.h>
int main(void)
{
fprintf(stdout, "Normal output\n");
fprintf(stderr, "Error message\n");
return 0;
}
For beginner console programs, printf() is the
usual choice for normal formatted output, while
stderr is useful for diagnostic or error messages.
5.25 Output Buffering โ Beginner View
Standard I/O may hold output temporarily in a buffer before sending it to its destination. A buffer is a temporary storage area.
For most beginner programs, you can simply think of
printf() and related functions as sending output
to stdout.
Buffering matters when a prompt must appear immediately or when output goes to files and other programs. For an interactive prompt without a newline, fflush(stdout) can request that buffered output be sent.
You do not need to master buffering to use ordinary
printf() correctly.
5.26 Complete Input and Output Program
The following program combines several ideas from this lesson.
#include <stdio.h>
int main(void)
{
int age;
double marks;
char grade;
char name[50];
printf("Enter your name: ");
fgets(name, sizeof name, stdin);
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your marks: ");
scanf("%lf", &marks);
printf("Enter your grade: ");
scanf(" %c", &grade);
printf("\n--- Student Details ---\n");
printf("Name : %s", name);
printf("Age : %d\n", age);
printf("Marks : %.2f\n", marks);
printf("Grade : %c\n", grade);
return 0;
}
What happens first?
The program reads a complete name using
fgets().
What happens next?
The numeric values are read using the appropriate
scanf() conversions.
Why " %c"?
The leading space allows scanf() to skip
whitespace before reading the grade.
5.27 Common Input & Output Mistakes
โ Mistake 1: Forgetting &
int age;
scanf("%d", age);
For a normal scalar variable this does not provide the
address that scanf() needs.
Correct:
scanf("%d", &age);
โ Mistake 2: Wrong double conversion
double value;
scanf("%f", &value);
For double input use:
scanf("%lf", &value);
โ Mistake 3: Using %s for a full sentence
scanf("%s", name);
This stops at whitespace.
Use fgets() when a complete line is needed.
โ Mistake 4: Forgetting newline
printf("Hello");
printf("World");
These may appear together on the same line.
printf("Hello\n");
printf("World\n");
5.28 Common Confusions
printf() is an output function.
It writes formatted information to stdout.
No. scanf() is an input function.
It reads formatted input from stdin.
For most scalar destinations, scanf() needs the
address at which it can store the converted value.
In an expression, a character array generally converts to a
pointer to its first element. That is what the
%s conversion expects.
No. %c does not skip leading whitespace.
Use " %c" when you want preceding whitespace
skipped.
No. The ordinary %s conversion reads a sequence
of non-whitespace characters.
No.
'0'is the digit character zero.'\0'is the null character.
5.29 Input & Output Concept Map
C Input & Output
โ
โโโ Standard I/O
โ โโโ <stdio.h>
โ
โโโ Output
โ โโโ printf()
โ โโโ putchar()
โ โโโ puts()
โ
โโโ Input
โ โโโ scanf()
โ โโโ getchar()
โ โโโ fgets()
โ
โโโ Format Specifiers
โ โโโ %d
โ โโโ %u
โ โโโ %f
โ โโโ %lf
โ โโโ %c
โ โโโ %s
โ
โโโ Escape Sequences
โ โโโ \n
โ โโโ \t
โ โโโ \\
โ โโโ \0
โ
โโโ Standard Streams
โโโ stdin
โโโ stdout
โโโ stderr
5.30 Safer Numeric Input with fgets and strtol
Check whether scanf successfully assigned the values before using them. For more controlled integer input, read a line with fgets and convert it with strtol. Check that digits were read, that the result is within range, and that any remaining characters are acceptable. Also handle an input line that is too long for the buffer.
Complete C program:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <ctype.h>
int main(void)
{
char line[80];
char *end;
long age;
puts("Enter age:");
if (!fgets(line, sizeof line, stdin)) return 1;
errno = 0;
age = strtol(line, &end, 10);
if (end == line) {
puts("Invalid age");
return 1;
}
while (isspace((unsigned char)*end)) ++end;
if (errno == ERANGE || *end != '\0' ||
age < 0 || age > 150) {
puts("Invalid age");
return 1;
}
printf("Accepted age: %ld\n", age);
return 0;
}
Expected output:
Enter age:
Accepted age: 21
Step-by-step explanation:
- With example input 21 followed by Enter, fgets reads a line.
- strtol converts the digits and sets end to the first unconverted character.
- Trailing whitespace is skipped and the range is checked.
5.31 Quick Revision
๐ scanf() is commonly used for formatted input.
๐ %d โ int
๐ %u โ unsigned int
๐ %c โ char
๐ %f โ floating-point output
๐ %lf โ double input with scanf()
๐ %s โ string
๐ \n โ new line
๐ &variable gives the address of a variable.
5.32 Quick MCQs
Select an answer first, then click Check Answer. A correct choice becomes green. If the choice is wrong, it becomes red and the correct option is shown in green. The explanation appears below after checking.
printf() is the standard formatted-output function declared in stdio.h.
scanf() reads formatted input from the standard input stream according to the format string.
%d is commonly used for signed decimal int input and output.
With scanf(), %lf expects a pointer to double. For printf(), a double value is printed with %f.
\n is the newline escape sequence.
5.33 ๐ฏ Programming Problems
Try each problem yourself first. Use ๐ป Solve It Yourself to write and test your C program. Use Hint only when needed, and open Show Program after attempting the problem.
Problem 1: Read two integers and print their sum.
Input: Two integers a and b.
Output: Print their sum.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int a, b;
scanf("%d %d", &a, &b);
printf("Sum = %d", a + b);
return 0;
}
Problem 2: Read three integers and print their average with decimal precision.
Input: Three integers.
Output: Print the average rounded to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int a, b, c;
double average;
scanf("%d %d %d", &a, &b, &c);
average = (a + b + c) / 3.0;
printf("Average = %.2f", average);
return 0;
}
Problem 3: Read a student's name, age and marks and display them.
Input: A single-word name, an integer age and marks.
Output: Print the name, age and marks with clear labels.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
char name[30];
int age;
float marks;
scanf("%29s %d %f", name, &age, &marks);
printf("Name = %s\n", name);
printf("Age = %d\n", age);
printf("Marks = %.2f", marks);
return 0;
}
Problem 4: Read the radius of a circle and print its area up to two decimal places.
Input: Radius of the circle.
Output: Print the area rounded to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
const double PI = 3.14159;
double radius;
double area;
scanf("%lf", &radius);
area = PI * radius * radius;
printf("Area = %.2f", area);
return 0;
}
Problem 5: Read two numbers and print their sum, difference, product and quotient.
Input: Two floating-point numbers a and b, where b is not zero.
Output: Print sum, difference, product and quotient rounded to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
double a, b;
scanf("%lf %lf", &a, &b);
printf("Sum = %.2f\n", a + b);
printf("Difference = %.2f\n", a - b);
printf("Product = %.2f\n", a * b);
printf("Quotient = %.2f", a / b);
return 0;
}
Problem 6: Read a character and print the character entered by the user.
Input: One character.
Output: Print the entered character.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
char ch;
scanf(" %c", &ch);
printf("Character = %c", ch);
return 0;
}
5.34 Key Takeaway
1. Identify the input data.
2. Choose the correct data type.
3. Use the correct scanf() format.
4. Process the data.
5. Use the correct printf() format.
This pattern is the foundation of almost every beginner coding-platform problem.
๐ Program Tracing โ Input & Output
Trace how scanf() stores input in variables and how printf() reads those values to produce output.
โ
๐ค Input & Output โ Interview Questions
๐ก Input & Output โ Extra Tips
- For scanf(), always match the conversion specifier with the correct pointer type.
- Remember the important difference: scanf() uses %lf for double, while printf() uses %f for double output.
- When reading a character after numeric input, understand why
scanf(" %c", &ch)is often safer thanscanf("%c", &ch). - When reading a string with
%s, use a field width such as%29sfor a 30-character array. - In coding tests, check the required output format carefully. Extra spaces, labels, or missing line breaks can cause a correct calculation to be judged wrong.
โ๏ธ Input & Output โ Extra Practice Questions
- Predict the exact output of
printf("%d %.2f", 10, 3.14159);. - Find the mistake in
double x; scanf("%f", &x);and correct it. - Explain why
scanf("%s", name)does not normally read a full name containing spaces. - Write one example that reads an integer, a double, and a character in the same program.
- Write a program that prints three values in neatly formatted separate lines using escape sequences.