Input and Output (I/O) operations are handled by standard library functions located in the <stdio.h> header file. These functions allow your program to display results and accept user data.
1. Formatted Output (printf())
The printf() function (Print Formatted) is used to display output to the console. It takes a format string and, optionally, one or more variables to be inserted into the string.
Syntax: printf("format string", variable1, variable2, ...);
Format Specifiers
Format specifiers are placeholders within the string that tell printf() what type of data to expect for substitution.
| Specifier | Used For | Example |
%d or %i | Integers (int, short) | printf("Age: %d", age); |
%f | Floating-point numbers (float) | printf("Price: %.2f", price); |
%lf | Double-precision floating-point numbers (double) | printf("Value: %lf", d_val); |
%c | Single character (char) | printf("Initial: %c", initial); |
%s | Strings (character arrays) | printf("Name: %s", name); |
Output Examples
Basic integer output:
int number = 42;
printf("The answer is %d.\n", number);
Controlling floating-point precision:Using %.2f displays the float with exactly two digits after the decimal point.
float pi = 3.14159;
printf("Pi rounded: %.2f\n", pi);
// Output: Pi rounded: 3.14
2. Formatted Input (scanf())
The scanf() function (Scan Formatted) is used to read formatted input from the standard input (usually the keyboard) and store it in a variable.
Syntax: scanf("format string", &variable1, &variable2, ...);
The Address-of Operator (&)
The most critical difference between printf() and scanf() is the use of the address-of operator (&) before the variable name.
scanf()needs to know the memory address where the input value should be stored, not the current value of the variable.- The
&symbol provides this address.
Input Examples
Reading an integer:
int user_age;
printf("Enter your age: ");
scanf("%d", &user_age); // Note the &
Reading a double and a character:
double weight;
char gender;
printf("Enter weight and gender (M/F): ");
scanf("%lf %c", &weight, &gender); // Note the %lf for double
Caution: When reading strings (
%s), you generally do not use the&operator because the string variable (which is an array) already represents the starting memory address.
3. Escape Sequences
Escape sequences are used inside string literals (like in printf()) to represent characters that are difficult or impossible to type directly.
| Sequence | Description |
\n | Newline (moves cursor to the next line) |
\t | Horizontal Tab |
\\ | Backslash character |
\" | Double quotation mark |
