Programs need to communicate with users. The most basic interactions are printing output and reading keyboard input.
printf()
printf() displays text or values. It only starts a new line when the format string contains \n.
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"KNOWLEDGE QUIZ
Formatted output
You can also insert values into a string with placeholders.
%d: integer%f: floating-point number%s: string
int length = 10;
int width = 5;
double area = length * width;
printf("Area = %d * %d = %.2f\n", length, width, area);Output:
Area = 10 * 5 = 50.00The placeholders correspond to the following arguments in order; %.2f formats a floating-point value with two decimal places.
printf("Area = %d * %d = %.2f\n", length, width, area);KNOWLEDGE QUIZ
Controlling the line ending
printf() does not add a newline automatically, so calls can continue on the same line. Put \n in the format string when the current line should end.
int num1 = 1;
int num2 = 2;
int num3 = 4;
int num4 = 8;
printf("%d, ", num1);
printf("%d, ", num2);
printf("%d, ", num3);
printf("%d...\n", num4);Output:
1, 2, 4, 8...scanf input
scanf reads standard input according to a format string: %d reads an int and %lf reads a double.
scanf("%127s", text) stores one whitespace-delimited token in a character array while limiting its width.
printf("Radius: ");
double r;
scanf("%lf", &r);
double area = 3.141592653589793 * r * r;
printf("Area = %.2f\n", area);One possible run:
Radius: 5
Area = 78.54Here, scanf("%lf", &r) reads a double directly, while 3.141592653589793 is the approximation of pi written explicitly in this example.
KNOWLEDGE QUIZ
Output Lab Bench
Run the three code cards in order and watch how each statement changes the terminal.
Calculate the distance between two points
Read two coordinate points and print the planar distance.
- Read x1, y1, x2, and y2 as four floating-point numbers.
- Apply the distance formula to compute the result.
- Print the distance rounded to two decimal places.
Build a temperature record card
Read one Celsius value, store it in clearly named variables, convert it to Fahrenheit, and print a compact report.
- Read one Celsius value with scanf("%lf", &value).
- Store the Fahrenheit result in a variable named fahrenheit.
- Create a string variable named reportTitle and print it together with the converted value.