A program becomes much more useful when it can communicate with the user.
For example, we may want to:
Display a message on the screen
Ask the user for their age
Take two numbers and calculate their sum
In C, these operations are called Input and Output (I/O).
What is Output?
Output means displaying information from the program to the user.
The most common function for output in C is printf().
#include <stdio.h>
int main()
{
printf("Hello, World!");
return 0;
}
Output:
Hello, World!
We can also print numbers and variables:
int age = 20;
printf("Age = %d", age);
Output:
Age = 20
Here, %d tells printf() that we want to display an integer.
What is Input?
Input means taking data from the user and using it in the program.
The most commonly used function for taking input in C is scanf().
For example:
int age;
scanf("%d", &age);
Here, the user enters an integer, and that value is stored in the age variable.
The & is related to the memory address of the variable. We'll understand exactly why it is needed when we learn pointers.
Simple Input and Output Example
Let's take the user's age and display it:
#include <stdio.h>
int main()
{
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("Your age is %d", age);
return 0;
}
If the user enters:
20
The output will be:
Enter your age: 20
Your age is 20
So the flow is:
User enters data
↓
scanf()
↓
Variable
↓
printf()
↓
Screen output
Common Format Specifiers
printf() and scanf() use format specifiers to work with different data types.
Data Type | Format Specifier |
|---|---|
|
|
|
|
|
|
|
|
For example:
int age = 20;
float price = 99.5;
char grade = 'A';
printf("%d\n", age);
printf("%f\n", price);
printf("%c\n", grade);
In Simple Words
Input is data received by the program, while output is information produced by the program.
In C, you'll mainly use:
printf()→ Outputscanf()→ Input
These two functions will appear again and again throughout your C programs, so getting comfortable with them is important.