Input and Output
In C programming, you can interact with the user using input and output functions. This means you can ask the user to enter something, and you can show results on the screen.
Output: printf()
We use the printf() function to display messages or variable values.
Example:
printf("Hello, World!\n");
int age = 20;
printf("Your age is: %d\n", age);
Input: scanf()
We use the scanf() function to take input from the user. You need to specify the data type you want to read and use the address-of operator (&).
Example:
int age;
printf("Enter your age: ");
scanf("%d", &age);
printf("You entered: %d\n", age);
Format Specifiers for Input and Output
- %d → for int
- %f → for float
- %lf → for double
- %c → for char
- %s → for string (array of characters)
Reading Multiple Values
You can also read multiple values at once:
int x, y;
printf("Enter two numbers: ");
scanf("%d %d", &x, &y);
printf("You entered: %d and %d\n", x, y);
Example:
#include <stdio.h>
int main() {
int age;
float weight;
char grade;
printf("Enter your age: ");
scanf("%d", &age);
printf("Enter your weight: ");
scanf("%f", &weight);
printf("Enter your grade: ");
scanf(" %c", &grade); // Note the space before %c
printf("\n--- Output ---\n");
printf("Age: %d\n", age);
printf("Weight: %.1f\n", weight);
printf("Grade: %c\n", grade);
return 0;
}