Lesson 9: Basic Input and Output: printf and scanf
These functions are part of the stdio.h library and are essential for user interaction.
Output: printf()
printf() is used to display output on the standard output stream (usually the console).
Format Specifiers
printf uses format specifiers to understand how to interpret and display variables.
| Specifier | Used for | Example |
|---|---|---|
%d or %i | Decimal integers (int) | printf("%d", age); |
%f | Floating point (float/double) | printf("%f", price); |
%.2f | Floating point (2 decimal places) | printf("%.2f", price); |
%c | Single character (char) | printf("%c", initial); |
%s | String (sequence of characters) | printf("%s", name); |
c #include <stdio.h>
int main() { int item_count = 5; float cost = 49.95; printf("Total items: %d. Cost: $%.2f.\n", item_count, cost); return 0; }
Input: scanf()
scanf() is used to read data from the standard input stream (keyboard).
Crucial Rule: When reading basic variables with scanf, you must pass the address of the variable using the address-of operator (&).
c #include <stdio.h>
int main() { int user_age; printf("Enter your age: "); // Notice the & before user_age scanf("%d", &user_age); printf("You are %d years old.\n", user_age); return 0; }
Failure to use & in scanf for non-array variables is a common mistake and leads to undefined behavior.