Level 06 ยท Input & Output

โŒจ๏ธ 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>.

Why this topic matters

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

Important

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
Important distinction

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);
Tip

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;
}
Character vs String

'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");
Remember

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);
Placement Tip

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.

Important exception: strings

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);
Memorize this rule
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
General rule

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;
}
Why is ch declared as int?

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;
}
Why is fgets() useful?

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.

Never use gets()

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.

Important

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.

Practical advice

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.

Interview point

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.

Why should you know this?

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

Confusion 1: Is printf() input or output?

printf() is an output function. It writes formatted information to stdout.

Confusion 2: Is scanf() output?

No. scanf() is an input function. It reads formatted input from stdin.

Confusion 3: Why does scanf() need &?

For most scalar destinations, scanf() needs the address at which it can store the converted value.

Confusion 4: Why no & before a string array?

In an expression, a character array generally converts to a pointer to its first element. That is what the %s conversion expects.

Confusion 5: Does %c skip spaces?

No. %c does not skip leading whitespace. Use " %c" when you want preceding whitespace skipped.

Confusion 6: Does %s read a sentence?

No. The ordinary %s conversion reads a sequence of non-whitespace characters.

Confusion 7: Is '\0' the same as '0'?

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:

  1. With example input 21 followed by Enter, fgets reads a line.
  2. strtol converts the digits and sets end to the first unconverted character.
  3. Trailing whitespace is skipped and the range is checked.
Remember: This example demonstrates a single line of input. A long line may be truncated; full applications should detect and handle that case.

5.31 Quick Revision

๐Ÿ“Œ printf() is commonly used for formatted output.

๐Ÿ“Œ 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.

1. Which function is commonly used to display formatted output?
2. Which function is commonly used to read formatted input?
3. Which format specifier is commonly used for an int?
4. Which specifier is used to read a double using scanf()?
5. Which escape sequence moves the output position to the next line?
PRACTICE

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.

๐Ÿ“ˆ Input & Output Practice Progress
Solved 0 / 6
Completed with Solution 0
Total Score 0 / 120
Completion 0%
A problem counts as Solved when all tests pass without opening the full solution. Problems completed after viewing the official solution are tracked separately.
1. Read Two Integers and Print Their Sum

Problem 1: Read two integers and print their sum.

Input: Two integers a and b.

Output: Print their sum.

2. Average of Three Integers

Problem 2: Read three integers and print their average with decimal precision.

Input: Three integers.

Output: Print the average rounded to two decimal places.

3. Display Student Details

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.

4. Area of a Circle

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.

5. Arithmetic Results

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.

6. Read and Print a Character

Problem 6: Read a character and print the character entered by the user.

Input: One character.

Output: Print the entered character.

5.34 Key Takeaway

๐ŸŽฏ For every input/output problem, remember:

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

๐Ÿ”Ž Program Tracing โ€” Input & Output

Trace how scanf() stores input in variables and how printf() reads those values to produce output.

INTERVIEW PREPARATION

๐ŸŽค Input & Output โ€” Interview Questions

1. What is the purpose of printf() in C?
2. What is the purpose of scanf() in C?
3. Why is & used with ordinary scalar variables in scanf()?
4. Why is there often a space before %c in scanf(" %c", &ch)?
5. What is the difference between %f and %lf for scanf()?
6. Why can scanf("%s", name) read only one word?
7. What is the difference between '\n' and '\t'?
PLACEMENT TIPS

๐Ÿ’ก 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 than scanf("%c", &ch).
  • When reading a string with %s, use a field width such as %29s for 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.
EXTRA PRACTICE

โœ๏ธ Input & Output โ€” Extra Practice Questions

  1. Predict the exact output of printf("%d %.2f", 10, 3.14159);.
  2. Find the mistake in double x; scanf("%f", &x); and correct it.
  3. Explain why scanf("%s", name) does not normally read a full name containing spaces.
  4. Write one example that reads an integer, a double, and a character in the same program.
  5. Write a program that prints three values in neatly formatted separate lines using escape sequences.
โ† Previous Topic: Data Types Next Topic: Operators โ†’