1.3 Input and Output
Programs need to communicate with users. The most basic interactions are printing output and reading keyboard input.
printf()
printf() displays text or variable values on the screen.
Some characters have special meaning in code, so they need escape sequences.
\\: backslash\': single quote\": double quote\n: newline\t: tab
printf("\"Hello\nWorld\"\n");Output:
"Hello
World"Format specifiers
printf() uses format specifiers (placeholders) to insert values into a string.
%d: integer%f: floating-point number%c: character%s: string
You can also control the format, for example %.2f keeps two decimal places.
int length = 10;
int width = 5;
double area = length * width;
printf("Area = %d * %d = %.2f\n", length, width, area);Output:
Area = 10 * 5 = 50.00Controlling the line ending
Unlike some languages, C’s printf() does not add a newline automatically. Line breaks are entirely up to you with \n.
int num1 = 1, num2 = 2, num3 = 4, num4 = 8;
printf("%d, ", num1);
printf("%d, ", num2);
printf("%d, ", num3);
printf("%d...\n", num4);Output:
1, 2, 4, 8...scanf()
scanf() reads text from the keyboard and stores it in a variable. When reading an ordinary variable, scanf() usually needs the variable’s address, taken with &.
Important: a scanf() format specifier must match the variable type: %d for int, and %lf for double.
#include <stdio.h>
int main(void) {
double r;
printf("Radius: ");
scanf("%lf", &r);
double area = 3.14159 * r * r;
printf("Area = %.2f\n", area);
return 0;
}One possible run:
Radius: 5
Area = 78.54Here, %lf reads a double, and &r passes the address of r to scanf() so it can write the value back into the variable.