C Lesson 9 – Input and Output | Dataplexa

Input and Output in C

Programs become meaningful only when they can take input from the user and display output.

In C, this interaction is mainly done using two functions:

  • printf() – for output
  • scanf() – for input

Both functions belong to the standard input/output library.


Standard Input and Output

C uses standard streams for communication:

  • Standard Input – keyboard
  • Standard Output – screen

To use input and output functions, we must include:


#include <stdio.h>

The printf() Function

The printf() function is used to display output on the screen.


printf("Hello, World!");

It can also display values of variables using format specifiers.

  • %d – integer
  • %f – float
  • %c – character
  • %s – string

int age = 20;
printf("Age is %d", age);

The scanf() Function

The scanf() function is used to read input from the user.

It requires:

  • A format specifier
  • The address of the variable (using &)

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

The & symbol tells C where to store the input value in memory.


Complete Example: Input and Output


#include <stdio.h>

int main() {
    int a, b, sum;

    printf("Enter first number: ");
    scanf("%d", &a);

    printf("Enter second number: ");
    scanf("%d", &b);

    sum = a + b;

    printf("Sum = %d", sum);
    return 0;
}

This program:

  • Reads two numbers from the user
  • Adds them
  • Displays the result

Common Mistakes Beginners Make

  • Forgetting & in scanf()
  • Using wrong format specifier
  • Not including <stdio.h>

These mistakes often cause runtime errors or unexpected results.


Mini Practice

  • Write a program to read and print your age
  • Read two numbers and display their product
  • Read a character and display it

Quick Quiz

Q1. Which header file is needed for input/output?

stdio.h

Q2. Which function is used to display output?

printf()

Q3. Why is & used in scanf?

To store input at the variable's memory address

Q4. Which format specifier is used for float?

%f

Q5. Can scanf read multiple values?

Yes, it can read multiple values in one statement