Introduction to C Input and Output
Text-based: Output goes to printer or monitor as text; Input comes from a file of text (words)
Output goes to special file, named “stdout”; Input from another special file named “stdin”.
Output
i. The
first argument to printf is a C string of characters. This argument “controls” everything printf() does.
WARNING: NOTHING will display unless
this string contains a “newline” character, which is represented as \n. Usually this character should be last in the
string.
ii. In
the simplest case, the entire first argument is simply copied to stdout:
printf(“This is the test
output\n”);
When executed, this displays:
This is the test output
on a line by itself. The quotation marks don’t display – these
simply mark the beginning and end of the string, for the C compiler. The \n causes the line to print, and moves
to the beginning of the next line.
iii. In
more complicated cases, the first argument contains the character %, followed
by a “conversion specifier”. Simple
conversion specifiers consist of single letters, each of which cause the next
argument’s value to be converted, and substituted for the conversion specifier,
while copying the first argument to stdout:
printf(“A[%d]=%d\n”, 10,
20); displays
A[10]=20
1. %d – integer argument
2. %s – string argument
3.
%f -- floating point number argument
iv. More complex specifiers allow you to control
1. How many characters, minimum, the converted quantity will occupy on the line (useful for creating tables)
2. Whether the extra characters should be added at the left, or the right of the number
3. Whether the extra characters should be zeros or spaces
4. Whether a leading plus sign should be printed
5. How many digits should appear to the right of the decimal point, when floating point numbers are printed
For details see the Input Output document.
Exercises:
i. The declarations in C should follow the “main() {“ line immediately.
i. Note: In C, the “equality test” is written ==, NOT =.
ii. An
“if test” is written:
if (test) {
do something if test was
“true”;
}
else {
do something if test was
false”
}
The “else” can be omitted. So can the
braces “{}” IF they enclose a single statement. Do NOT follow the first “}” with a semi-colon, or C may not
understand the “else”.
i. A
“while loop” may be useful here:
while (test) {
do something;
}
repeats “do something (which can be a sequence of statements), over and over,
until the “test” is false. (If the test
is false the first time, it sodes nothing.)