0
0
Cprogramming~5 mins

Multiple input and output in C

Choose your learning style9 modes available
Introduction

We use multiple input and output to handle more than one piece of information at the same time. This helps programs interact with users or other programs better.

When you want to ask a user for their name and age together.
When reading several numbers from a file to process them.
When printing multiple results like sum and average at once.
When a program needs to get multiple answers from a user in one go.
When you want to display several pieces of information clearly.
Syntax
C
scanf("%d %d", &var1, &var2);
printf("%d %d", var1, var2);

Use scanf to read multiple inputs by listing format specifiers and variables separated by spaces.

Use printf to print multiple outputs by listing format specifiers and variables in order.

Examples
This reads two integers from the user and stores them in a and b.
C
int a, b;
scanf("%d %d", &a, &b);
This prints the two integers stored in a and b separated by a space.
C
printf("%d %d", a, b);
This reads two floating-point numbers and prints them with 2 decimal places.
C
float x, y;
scanf("%f %f", &x, &y);
printf("%.2f %.2f", x, y);
Sample Program

This program asks the user to enter two numbers. It reads both numbers at once using scanf. Then it calculates their sum and product and prints both results separately.

C
#include <stdio.h>

int main() {
    int num1, num2;
    printf("Enter two numbers separated by space: ");
    scanf("%d %d", &num1, &num2);

    int sum = num1 + num2;
    int product = num1 * num2;

    printf("Sum: %d\n", sum);
    printf("Product: %d\n", product);

    return 0;
}
OutputSuccess
Important Notes

Always provide the address of variables to scanf using &.

Separate format specifiers in scanf and printf with spaces to match input/output format.

Be careful to match the data types in format specifiers with the variables you use.

Summary

Multiple input and output lets you handle several values at once.

Use scanf with multiple format specifiers and variable addresses to read inputs.

Use printf with multiple format specifiers and variables to print outputs.