Paramclasses Academy - Blog

Tutorials Details

←
Post 6 of 15
→

What is Input and Output in C programming

What is Input and Output in C programming

October 13, 2026

1. Introduction

Input and output (I/O) are essential parts of C programming. They allow a program to communicate with users by accepting data and displaying results.

For example, a calculator accepts two numbers from the user, adds them, and displays the result. In C, common functions for these tasks include printf() and scanf().

By the end of this module, you will learn how to:

  • Display text and values using printf().

  • Accept user input using scanf().

  • Use format specifiers correctly.

  • Read characters and strings.

  • Validate input and avoid common errors.

2. What Is Output in C?

Output is the information a program displays to the user. C commonly uses the printf() function, declared in the standard header file stdio.h.

Syntax

printf("format string", arguments);

Example:

#include <stdio.h>

int main(void) {
    printf("Hello, World!\n");
    return 0;
}

Output:

Hello, World!

Explanation:

  • #include <stdio.h> provides declarations for standard input/output functions.

  • printf() displays formatted output.

  • \n moves the cursor to a new line.

  • return 0; indicates successful program completion.

3. Using printf() to Display Variables

You can use printf() to display variable values as well as ordinary text.

#include <stdio.h>

int main(void) {
    int age = 20;
    float marks = 87.5f;
    char grade = 'A';

    printf("Age: %d\n", age);
    printf("Marks: %.1f\n", marks);
    printf("Grade: %c\n", grade);

    return 0;
}

Output:

Age: 20
Marks: 87.5
Grade: A

The format specifier tells printf() how to display the corresponding argument.

Format specifier

Purpose

Example

%d

Signed decimal integer

25

%u

Unsigned decimal integer

25

%f

Floating-point value

12.500000

%.2f

Floating-point value with two digits after the decimal

12.50

%c

Single character

A

%s

Null-terminated string

Hello

%ld

long int

123456L

%zu

Value of type size_t

sizeof result

Important: The format specifier must match the argument's type. A mismatch can cause undefined behavior.

4. What Is Input in C?

Input is data provided to a program by a user or another source. The scanf() function is commonly used to read formatted input from standard input, usually the keyboard.

Syntax

scanf("format string", &variable);

Example:

#include <stdio.h>

int main(void) {
    int age;

    printf("Enter your age: ");

    if (scanf("%d", &age) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    printf("Your age is %d\n", age);

    return 0;
}

Sample output:

Enter your age: 21
Your age is 21

Why do we use & in scanf()?

The & operator obtains the address of a variable. scanf() needs that address so it can store the entered value in the variable.

For example:

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

Here, &number gives scanf() the address where the integer value should be stored.

For a character array used to store a string, you generally do not use &:

char name[30];
scanf("%29s", name);

The array name converts to a pointer to its first element in this context.

5. Taking Input of Different Data Types

Different data types require appropriate format specifiers.


#include <stdio.h>

int main(void) {
    int number;
    float price;
    double distance;
    char grade;

    printf("Enter an integer: ");
    if (scanf("%d", &number) != 1) {
        printf("Invalid integer.\n");
        return 1;
    }

    printf("Enter a price: ");
    if (scanf("%f", &price) != 1) {
        printf("Invalid price.\n");
        return 1;
    }

    printf("Enter a distance: ");
    if (scanf("%lf", &distance) != 1) {
        printf("Invalid distance.\n");
        return 1;
    }

    printf("Enter a grade: ");
    if (scanf(" %c", &grade) != 1) {
        printf("Invalid grade.\n");
        return 1;
    }

    printf("\n--- Entered Data ---\n");
    printf("Integer: %d\n", number);
    printf("Price: %.2f\n", price);
    printf("Distance: %f\n", distance);
    printf("Grade: %c\n", grade);

    return 0;
}

Important format specifiers for scanf()

Data type

Format specifier

Example declaration

int

%d

int age;

unsigned int

%u

unsigned int count;

float

%f

float price;

double

%lf

double distance;

char

%c

char grade;

Character array

%s

char name[30];

long int

%ld

long int population;

Remember: For printf(), use %f to print a double value. For scanf(), use %lf to read a double value.

6. Escape Sequences in C

Escape sequences are special character combinations used in strings and character literals.

Escape sequence

Meaning

\n

New line

\t

Horizontal tab

\\

Backslash character

\"

Double quotation mark

\'

Single quotation mark

\r

Carriage return

\0

Null character

Example:

#include <stdio.h>

int main(void) {
    printf("Name:\tAlex\n");
    printf("Language:\tC\n");
    printf("He said, \"Hello!\"\n");

    return 0;
}

Output:

Name:   Alex
Language:   C
He said, "Hello!"

The \t sequence inserts a horizontal tab, so the exact visual spacing depends on the terminal.

7. Reading a Single Character

Use %c to read a character. However, whitespace such as a newline left behind by earlier input can be read too.

A leading space in " %c" tells scanf() to skip whitespace before reading the character.

#include <stdio.h>

int main(void) {
    char choice;

    printf("Enter Y or N: ");

    if (scanf(" %c", &choice) != 1) {
        printf("Input error.\n");
        return 1;
    }

    printf("Your choice: %c\n", choice);

    return 0;
}

Sample output:

Enter Y or N: Y
Your choice: Y

8. Reading Strings in C

A string in C is a character array terminated by the null character '\0'.

Using scanf() with %s

#include <stdio.h>

int main(void) {
    char name[30];

    printf("Enter your first name: ");

    if (scanf("%29s", name) != 1) {
        printf("Input error.\n");
        return 1;
    }

    printf("Hello, %s!\n", name);

    return 0;
}

The width limit %29s leaves room for the terminating null character in the 30-character array.

Limitation: %s stops reading at whitespace, so it cannot read a full name such as Alex Morgan as one string.

Using fgets() to read a full line

Use fgets() when you need to accept spaces.

#include <stdio.h>
#include <string.h>

int main(void) {
    char name[100];

    printf("Enter your full name: ");

    if (fgets(name, sizeof name, stdin) == NULL) {
        printf("Input error.\n");
        return 1;
    }

    name[strcspn(name, "\n")] = '\0';

    printf("Hello, %s!\n", name);

    return 0;
}

Sample output:

Enter your full name: Alex Morgan
Hello, Alex Morgan!

Here, fgets() reads a line with spaces, and strcspn() helps remove the newline if it was captured.

9. The Difference Between printf(), scanf(), and puts()

Function

Purpose

Example

printf()

Displays formatted output

printf("Age: %d", age);

scanf()

Reads formatted input

scanf("%d", &age);

puts()

Displays a string followed by a newline

puts("Hello");

getchar()

Reads one character from standard input

int ch = getchar();

fgets()

Reads a line into a character array

fgets(name, sizeof name, stdin);

For beginner programs, printf() and scanf() are important starting points. For line-based text input, fgets() is often a better choice.

10. Practical Example: Simple Calculator

This program accepts two numbers and an operator, then performs the requested arithmetic operation.


#include <stdio.h>

int main(void) {
    double a, b;
    char operator;

    printf("Enter an expression (e.g., 10 + 5): ");

    if (scanf("%lf %c %lf", &a, &operator, &b) != 3) {
        printf("Invalid input.\n");
        return 1;
    }

    switch (operator) {
        case '+':
            printf("Result: %.2f\n", a + b);
            break;

        case '-':
            printf("Result: %.2f\n", a - b);
            break;

        case '*':
            printf("Result: %.2f\n", a * b);
            break;

        case '/':
            if (b == 0.0) {
                printf("Error: Division by zero.\n");
                return 1;
            }
            printf("Result: %.2f\n", a / b);
            break;

        default:
            printf("Invalid operator.\n");
            return 1;
    }

    return 0;
}

Sample output:

Enter an expression (e.g., 10 + 5): 10 + 5
Result: 15.00

This example demonstrates input parsing, format specifiers, output formatting, a switch statement, and division-by-zero handling.

11. Common Mistakes to Avoid

  • Forgetting & when using scanf() with ordinary scalar variables.

  • Using %f instead of %lf when reading a double.

  • Using %s without a field width for a fixed-size character array.

  • Assuming %s can read spaces in a full name.

  • Ignoring the return value of scanf().

  • Using %c without considering whitespace left in the input stream.

  • Passing a value whose type does not match the printf() format specifier.

  • Assuming that valid numeric syntax always means a value is within the range required by the program.

12. Practice Exercises

1. Write a program that reads an integer and prints it.

Show hint

2. Write a program that reads two floating-point numbers and prints their sum.

Show hint

3. Write a program that reads a character and displays it.

Show hint

4. Read a full name containing spaces and print a greeting.

Show hint

13. Interview Questions

Q1. What is input and output in C?

Input is data received by a program, while output is information produced by the program.

Q2. What is the purpose of stdio.h?

It declares standard input/output functions such as printf(), scanf(), getchar(), and fgets().

Q3. Why is & used in scanf()?

It supplies the address where the function should store the input value.

Q4. What is the difference between %f and %lf?

For printf(), %f is used to print a double value. For scanf(), %f reads a float, while %lf reads a double.

Q5. What does \n mean?

It represents a newline character.

Q6. What is the difference between scanf("%s", name) and fgets()?

%s reads a sequence of non-whitespace characters. fgets() can read spaces and stops at a newline or its size limit.

Q7. Why should we check the return value of scanf()?

It reports how many input items were successfully assigned, helping the program detect invalid or incomplete input.

14. Quick Revision

  • printf() displays formatted output.

  • scanf() reads formatted input.

  • stdio.h declares standard input/output functions.

  • Use the correct format specifier for each data type.

  • Use & with scanf() for ordinary scalar variables.

  • Use a width limit when reading into a fixed-size array with %s.

  • Use fgets() for text containing spaces.

  • Check input function return values.

  • Validate input before using it in calculations.

15. Homework

Create a Student Information Program that:

  1. Accepts a student's name, age, roll number, and marks.

  2. Reads the student's full name, including spaces.

  3. Validates input before using the values.

  4. Displays all information in a neatly formatted output.

  5. Displays marks with two digits after the decimal point.

←
Post 6 of 15
→