โจ๏ธ Input & Output in C
A program becomes interactive when it can receive information from the user and display useful results.
In C, most beginner-level console input and output is handled through the standard I/O library: <stdio.h>.
Variables allow a program to store information, but input and output allow a program to communicate with the outside world.
Almost every practical C program uses some combination of reading input, processing it, and producing output.
6.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
6.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 |
6.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.
6.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.
6.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);
Use a format specifier appropriate for the type of the argument rather than choosing one based only on the value.
6.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 argument is subject to the default
argument promotions when passed to the variadic
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
6.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.
6.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.
6.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'.
6.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.
6.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;
}
6.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.
6.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); |
6.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 exists because scanf() receives
pointers to the destination types, while arguments passed to
the variadic part of printf() undergo the default
argument promotions.
6.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.
6.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.
6.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;
}
6.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 a simple scanf("%s", ...), it can read
spaces within a line and allows the program to specify the
maximum number of characters that can be stored.
6.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.
6.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.
6.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.
6.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.
When designing beginner programs, be deliberate about which
input technique you use. Mixing token-oriented
scanf() input and line-oriented fgets()
requires careful newline handling.
6.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.
6.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.
6.25 Output Buffering โ Beginner View
Output is not always sent to the final destination one character at a time. Standard I/O can use buffering.
For most beginner programs, you can simply think of
printf() and related functions as sending output
to stdout.
Buffering becomes important when working with interactive programs, files, pipelines, or when you need output to appear immediately.
You do not need to master buffering to use ordinary
printf() correctly.
6.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.
6.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");
6.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.
6.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
6.30 Quick Revision
| Concept | Remember |
|---|---|
| Header | #include <stdio.h> |
| Formatted output | printf() |
| Formatted input | scanf() |
| One-character input | getchar() |
| One-character output | putchar() |
| Line input | fgets() |
| String output | puts() |
| Integer output | %d |
| Float input | %f |
| Double input | %lf |
| Character | %c |
| String | %s |
| Newline | \n |
| String terminator | \0 |
๐ง Test Your Understanding
& generally used with scalar variables
in scanf()?
Because scanf() needs the address of the destination
object so that it can store the converted input value there.
%f and
%lf in scanf()?
%f expects a pointer to float,
while %lf expects a pointer to double.
" %c" sometimes used instead of
"%c"?
The leading whitespace tells scanf() to skip
preceding whitespace before reading the character.
fgets().
\0 represent in a C string?
It is the null character used to mark the end of a null-terminated C string.
๐ฏ Interview Preparation
1. What is printf()?
printf() is a standard C library function used
to produce formatted output on stdout.
2. What is scanf()?
scanf() is a standard C library function used
to read formatted input from stdin.
3. Why is & used in scanf()?
For most scalar variables, it supplies the address where
scanf() should store the converted value.
4. Why is & not used with a character array in %s?
A character array expression generally converts to a pointer
to its first element, which is what the %s
conversion expects.
5. Difference between %f and %lf in scanf()?
%f expects float *, while
%lf expects double *.
6. What is the difference between getchar() and scanf("%c")?
Both can read characters, but they are different interfaces.
getchar() directly reads one character from
stdin, while scanf() performs a
formatted conversion.
7. What is fgets()?
fgets() reads characters from a stream into a
character array, stopping when the buffer is full, a newline
is read, or end-of-file/error is encountered.
8. What is the purpose of stderr?
stderr is the standard error stream, commonly
used for diagnostic and error messages.
๐ผ Placement Tips
Memorize the difference between
printf() and scanf().
Remember:
scanf("%f", &x) for float and
scanf("%lf", &x) for double.
Know why scanf(" %c", &ch) uses a leading
space.
Understand why fgets() is useful for lines
containing spaces.
Know the difference between 'A',
"A", and '\0'.
Be able to explain the role of
stdin, stdout, and
stderr.
Problem 1 โ Read and Display a Number
Not StartedRead one integer and display it using the exact format:
Number = value
scanf("%d", &number) to read the
integer and printf() to display it.
Your Program
Input
Output
#include <stdio.h>
int main(void)
{
int number;
scanf("%d", &number);
printf("Number = %d\n", number);
return 0;
}
Problem 2 โ Sum, Difference and Product
Not StartedRead two integers and display their sum, difference, and product using these labels:
Sum = ...
Difference = ...
Product = ...
scanf() statement,
then use arithmetic expressions.
Your Program
Input
Output
#include <stdio.h>
int main(void)
{
int a, b;
scanf("%d %d", &a, &b);
printf("Sum = %d\n", a + b);
printf("Difference = %d\n", a - b);
printf("Product = %d\n", a * b);
return 0;
}
Problem 3 โ Display a Floating-Point Value
Not StartedRead a floating-point value and display it with exactly two digits after the decimal point.
Value = 12.35
double, read it with %lf,
and print it with %.2f.
Your Program
Input
Output
#include <stdio.h>
int main(void)
{
double value;
scanf("%lf", &value);
printf("Value = %.2f\n", value);
return 0;
}
Problem 4 โ Read a Character
Not StartedRead one non-whitespace character and display it using:
Character = X
scanf(" %c", &ch). The leading space
causes preceding whitespace to be skipped.
Your Program
Input
Output
#include <stdio.h>
int main(void)
{
char ch;
scanf(" %c", &ch);
printf("Character = %c\n", ch);
return 0;
}
Problem 5 โ Read a Word and Greet the User
Not StartedRead one word and display:
Hello, word!
The input will contain a single word without spaces.
%s conversion.
Remember to provide a width limit when using scanf()
with a fixed-size character array.
Your Program
Input
Output
#include <stdio.h>
int main(void)
{
char name[30];
scanf("%29s", name);
printf("Hello, %s!\n", name);
return 0;
}
Read a student name, age, and marks and display all three values using suitable format specifiers.
Read length and width and print the area and perimeter.
Read a Celsius temperature as a double and display it with two decimal places.
Read a character and display it using %c.
Read two double values and print their sum with exactly two decimal places.
Use fgets() to read a complete sentence and
display it using printf() or puts().
๐ Key Takeaway
Input and output form the communication layer of a C program.
The most important functions to remember are:
printf()โ formatted outputscanf()โ formatted inputgetchar()โ read one characterputchar()โ write one characterfgets()โ read a lineputs()โ write a string with a newline
Most importantly, understand the difference between format specifiers, addresses, whitespace, and strings. These concepts will appear repeatedly throughout the rest of the C course.
C Input & Output
|
+----------------+----------------+
| |
INPUT OUTPUT
| |
+----+----+ +----+----+
| | | | | |
scanf getchar fgets printf putchar puts
| |
+-------------+-------------------+
|
Format Specifiers
|
+-----------+-----------+
| | | |
%d %f %c %s