What is the output of the program

Day 6





week 1

Most of your programs will require you to display information on the screen or read information from the keyboard. Most of the example programs presented so far have already worked with it, even if you may not have understood how everything is connected. Today you will learn:

  • Understand the basics of input / output statements in C.
  • how to display information with the library functions and on the screen
  • how to format information on the screen
  • how to read data from the keyboard using the library function

Today's lesson is not meant to cover all of these topics, but just to provide the basic information so that you can start writing real programs. We'll discuss these topics in more detail later in this book.

Display information on the screen

In most of your programs, you will probably want to see output on the screen. And that is most often done through the two library functions of C, and.

The function printf ()

The function is part of the C standard library. It is probably the most flexible option for displaying data on the screen. You have already encountered many examples in this book. Now you should learn how the function works.

The output of a text message on the screen is easy. Call the function and pass it the appropriate message in double quotes. For example, to put "" on the screen, write

printf ("An error occurred!");

In most cases, however, you not only have to output a text message, but also the value of program variables. This is a little more complicated than just printing a message. For example, suppose you want to display the value of the numeric variable on the screen together with explanatory text and this text should begin on a new line. To do this, you could use the function like this:

printf ("\ nThe value of x is% d", x);

Given that the value is of, the output on the screen would then be:

The value of x is 12

In this example two arguments are passed. The first argument is in double quotation marks and is called the format string. The second argument is the name of the variable () that contains the value to be output.

printf () - format strings

A format string specifies how the output is to be formatted. See the three possible components of a format string below:

  • Literal text is displayed exactly as it is entered in the format string. In the example above, this literal string consists of the characters (in) to (which is not part of it).
  • Escape sequences offer special options for formatting. An escape sequence consists of a backslash followed by a single character. In our example above, there is an escape sequence. The escape sequence is known as the new line character and means, "Go to the beginning of the next line." Escape sequences are also used to output certain characters. The most common escape sequences are listed in Table 6.1. See Chapter 14, "Advanced Pointers," for a complete list.
  • Conversion specifiers consist of a percent sign () followed by another character. In the example above, the conversion specifier is. A conversion specifier tells how the variable to be output is to be interpreted. With you indicate that the variable is to be interpreted as a decimal number of the type (with sign).

sequence

importance

Beep (acoustic signal)

Backspace

New line

Horizontal tab

Backslash

Question mark

Single quotation marks

Table 6.1: The most common escape sequences.

The escape sequences of printf ()

Escape sequences are used to control the position of the output by moving the cursor on the screen. But they are also used to output characters that otherwise have a special meaning. For example, to output a single backslash, you have to include a double backslash () in the format string. The first backslash indicates that the second backslash is to be understood as a literal character and not as the start of an escape sequence. In general, you use the backslash to indicate that the next character is to be interpreted in a special way. See some examples below:

sequence

importance

The character n

New line

The double quotation mark

Beginning or end of a string

Listing 6.1 uses some of the most common escape sequences.

Listing 6.1: Escape sequences together with printf ().

1: / * Examples of the most common escape sequences * /
2:
3: #include
4:
5: #define EXIT 3
6:
7: int menue_option_einlesen (void);
8: void report_view (void);
9:
10: int main (void)
11: {
12: int option = 0;
13:
14: while (option! = EXIT)
15: {
16: option = menue_option_einlesen ();
17:
18: if (option == 1)
19: printf ("\ nAcoustic signal from the computer \ a \ a \ a");
20: else
21: {
22: if (option == 2)
23: report_ displays ();
24: }
25: }
26: printf ("You chose the exit option! \ N");
27:
28: return 0;
29: }
30:
31: int menue_option_einlesen (void)
32: {
33: int selection = 0;
34:
35: do
36: {
37: printf ("\ n");
38: printf ("\ n1 - Acoustic signal from the computer");
39: printf ("\ n2 - display report");
40: printf ("\ n3 - quit");
41: printf ("\ n");
42: printf ("\ nEnter your choice:");
43:
44: scanf ("% d", & selection);
45:
46:} while (selection <1 || selection> 3);
47:
48: return selection;
49: }
50:
51: void report_display (void)
52: {
53: printf ("\ nSAMPLE REPORT");
54: printf ("\ n \ n Sequence \ tMeaning");
55: printf ("\ n ========= \ t =======");
56: printf ("\ n \ a \ t \ tBeep (acoustic signal)");
57: printf ("\ n \ b \ t \ tBackspace");
58: printf ("\ n ... \ t \ t ...");
59: }

1 - Acoustic signal from the computer
2 - View the report
3 - leave

Enter your choice: 1

Acoustic signal from the computer

1 - Acoustic signal from the computer
2 - View the report
3 - leave

Enter your choice: 2

SAMPLE REPORT
Sequence meaning
========= =======
\ a Beep (acoustic signal)
\ b backspace
... ...
1 - Acoustic signal from the computer
2 - View the report
3 - leave

Enter your choice: 3
You have chosen the Exit option!

Listing 6.1 seems rather long compared to the previous examples, and it contains a few additions that should be examined more closely. The header file is included in line 3 as it is used in this listing. Line 5 defines a constant named. From the section "Saving Data: Variables and Constants" from Day 2, you may remember that you use to equate the constant with the value. Lines 7 and 8 contain function prototypes. This program uses two functions: and. The function is defined in lines 31 to 49. It is similar to the menu function from Listing 5.5. Lines 37 and 41 contain calls to in which the escape sequence is issued. Lines 38, 39, 40 and 42 contain text to be output in addition to the new line escape character. Line 37 could be left out if you changed line 38 as follows:

printf ("\ n \ n1 - Acoustic signal from the computer");

However, with the additional line 37, the program is easier to read.

Let's take a look at the function. A loop begins in line 14, the statements of which are run through as long as is not equal. Since is a constant, you could have replaced it with. Then the program would not be so clear. Line 16 assigns the code to the variable selected by the user, which is then analyzed in an instruction in lines 18 to 25. If the user dials, line 19 outputs the new line character, a message and three warning tones. And when the user chooses, line 23 calls the function.

The function is defined in lines 51 to 59. This simple function shows how easy it is to display information formatted with and the escape sequences on the screen. You have already learned about the new line symbol. On lines 54 through 58 you will also find the escape character for the tabulator:. The tab character aligns the columns of the report vertically. Lines 56 and 57 may seem a bit confusing at first, but if you go through them from left to right, you should quickly see the point. Line 56 outputs a new line (), then a backslash () followed by the letter and then two tabs (). The line ends with a descriptive text (). Line 57 follows the same pattern.

This program outputs the first two lines of Table 6.1 along with a title for the report and column headings. In Exercise 9 at the end of this lesson, you have to complete this program so that it prints the rest of the table.

The printf () conversion specifiers

The format string must contain a conversion specifier for each output variable. The function outputs each variable as specified by the corresponding conversion specifier. You will learn more about this on Day 15, “Working with Files”. For now, just make sure you are always using the conversion specifier that matches the type of variable you want to output.

What exactly is meant by that? If you want to output a signed decimal number (type or), use the conversion specifier. Use the specifier for unsigned decimal numbers (type or) and the specifier for floating point variables (type or). The most commonly used conversion specifiers are summarized in Table 6.2

Specifier

importance

converted types

Simple sign

char

Signed decimal number

int, short

Large signed decimal number

long

Floating point number

float, double

Character string

char arrays

Unsigned decimal number

unsigned int, unsigned short

Large unsigned decimal number

unsigned long

Table 6.2: The most common conversion specifiers.

All programs that use
should include the header file.

The literal text of a format specifier is anything that is neither an escape sequence nor a conversion specifier. Literal text is output exactly as it is, including all spaces.

Can you also output values ​​from several variables? A single statement can return an unlimited number of variables, but the format string must contain a conversion specifier for each variable. The conversion specifiers are paired with the variables and are read from left to right. So when you write

printf ("rate =% f, amount =% d", rate, amount);

pairs the variable with the specifier and the variable with the specifier. The positions of the conversion specifier in the format string determine the position of the output. If more variables are passed than there are conversion specifiers, the redundant variables are not output. On the other hand, if there are more specifiers than variables, the unused specifiers output "garbage".

You cannot only output the values ​​of variables with. Any valid C expression can serve as an argument. For example, to print the sum of and you could write

z = x + y;
printf ("% d", z);

But you could also write

printf ("% d", x + y);

Listing 6.2 shows you how to use. On day 15 you will receive more detailed information about this feature.

Listing 6.2: Output numeric values ​​with printf ().

1: / * Example that outputs numeric values ​​with printf (). * /
2:
3: #include
4:
5: int a = 2, b = 10, c = 50;
6: float f = 1.05, g = 25.5, h = -0.1;
7:
8: int main (void)
9: {
10: printf ("\ nDecimal values ​​without tabs:% d% d% d", a, b, c);
11: printf ("\ nDecimal values ​​with tabs: \ t% d \ t% d \ t% d", a, b, c);
12:
13: printf ("\ nThree floating point numbers in one line: \ t% f \ t% f \ t% f", f, g, h);
14: printf ("\ nThree floating point numbers in three lines: \ n \ t% f \ n \ t% f \ n \ t% f",
15: f, g, h);
16: printf ("\ nThe odds are% f %%", f);
17: printf ("\ nThe result of% f /% f =% f \ n", g, f, g / f);
18:
19: return 0;
20: }

Decimal values ​​without tabs: 2 10 50
Decimal values ​​with tabs: 2 10 50
Three floating point numbers in one line: 1.050000 25.500000 -0.100000
Three floating point numbers in three lines:
1.050000
25.500000
-0.100000
The quota is 1,050000%
The result of 25.500000 / 1.050000 = 24.285715

Listing 6.2 prints nine lines. Lines 10 and 11 each print three decimal numbers:, and. In line 10 these numbers are simply one behind the other without tabs, in line 11 they are separated by tabs. Lines 13 and 14 each output three variables of the type:, and. In line 13 they are output in one line and in line 14 in three lines. Line 16 prints a floating point number, followed by a percent sign. Since a percent sign usually indicates that a variable is to be output, you must put two percent signs in a row to display a single percent sign. This corresponds to the procedure for the backslash escape character. Finally, line 17 illustrates the output of expressions such as.

What you should do

Do not try to put multiple lines of text in one statement. In most cases, it is clearer if you split several lines into several - statements instead of just using one - statement and spiking it with new line characters ().

Don't forget the new line character if you want to display multiple lines of information in multiple statements.

Pay attention to the spelling of. Many C programmers make mistakes and write frequently. The header file is written without.

The function printf ()

#include
printf (format string [, arguments, ...]);

is a function that takes a format string with conversion specifiers and an associated one for each conversion specifier. The function outputs the formatted information to the standard output device, usually the screen. If you are using, you must include the header file for standard input / output,,.

It is mandatory, but it is optional. There must be a conversion specifier for each argument. The most common conversion specifiers are shown in Table 6.2.

It can also contain escape sequences. Table 6.1 lists the most commonly used escape sequences.

Here are some examples of calls and their output:

Example 1: input

#include
int main (void)
{
printf ("This is an example of output! \ n");
return 0;
}

Example 1: output

This is an example of an output!

Example 2: input

printf ("This command prints a character,% c \ ne a number,
% d \ nand a floating point number,% f \ naus ", 'z', 123, 456.789);

Example 2: output

This command gives a character, e.g.
a number, 123
and a floating point number, 456,789
out

Output messages with puts ()

The function can also be used to display text on the screen. However, it does not allow the output of numeric variables. The function takes a simple string as an argument and outputs it, whereby a new line is automatically started at the end. The instruction

puts ("Hello, world.");

therefore has the same effect as

printf ("Hello, world. \ n");

You can also use escape sequences (inclusive) in the string that is passed. They have the same effect as with the function (Table 6.1 lists the most common escape sequences).

As with, the header file must be specified in every program that uses it (if not already done).

What you should be doing

What not

Whenever you want to output text without additional variables, use the function instead of.

Do not try to use conversion specifiers with the statement.

The puts () function

#include
puts (string);

is a function that outputs a string to the standard output device, usually the screen. If you use, you have to include the header file for standard input / output. automatically appends a new line character to the end of the string to be output. The format string may contain escape sequences.The most common escape sequences can be found in Table 6.1.

Here are some examples of calls and their output:

Example 1: input

puts ("This text is output with the puts () function!");

Example 1: output

This text is output with the puts () function!

Example 2: input

puts ("This output is on the first line. \ nThis is on the second line.");
puts ("This output is on the third line.");
puts ("With printf () the four lines would be in two lines!");

Example 2: output

This output is on the first line.
This in the second.
This output occurs in the third line.
With printf () the four lines would be in two lines!

Read in numerical data with scanf ()

Just as often as programs have to output data to the screen, they are forced to read data from the keyboard. The library function is the most flexible.

The function reads data that correspond to a specified format from the keyboard and assigns it to one or more program variables. As before, also uses a format string to define the format of the input. The same conversion specifiers are used in the format string as for. For example, the instruction reads

scanf ("% d", & x);

Enter a decimal number from the keyboard and assign it to the integer variable. Correspondingly, the following statement reads a floating point number from the keyboard and then assigns it to the variable:

scanf ("% f", & rate);

But what is the ampersand () doing in front of the variable name? The symbol is the address operator of C, which is described in detail on day 8, "Pointer". At the moment it is enough to remember that the symbol must be set in front of every numeric variable name in the argument list of (unless the variable is a pointer, which will also be explained on day 8).

You can read in several values ​​with a single function. The prerequisite, however, is that you specify several conversion specifiers in the format string and several variable names (each preceded by an -sign) in the argument list. The following statement takes an integer and a floating point value and assigns them to the variables, respectively:

scanf ("% d% f", & x, & rate);

When entering multiple variables, use whitespace characters to divide the entry into fields. Whitespace characters include spaces, tabs, or newline characters. Each conversion specifier in the format string is matched with an input field. The end of an input field is marked with a whitespace symbol.

That makes you pretty flexible. An input for the above call could look like this, for example:

10 12.45

Or you could enter the values ​​like this:

10 12.45

Or so:

10
12.45

As long as there is a whitespace character between the values, any value can be assigned to its variable.

As with the other functions presented today, programs that use must include the header file. Listing 6.3 shows an example of the use of (see also the chapter on day 15).

Listing 6.3: Reading in numerical values ​​with scanf ().

1: / * Example of using scanf () * /
2:
3: #include
4:
5: #define EXIT 4
6:
7: int menue_option_einlesen (void);
8:
9: int main (void)
10: {
11: int option = 0;
12: int int_var = 0;
13: float float_var = 0.0;
14: unsigned unsigned_var = 0;
15:
16: while (option! = EXIT)
17: {
18: option = menue_option_einlesen ();
19:
20: if (option == 1)
21: {
22: puts ("\ nEnter a signed decimal number \
(e.g. -123) ");
23: scanf ("% d", & int_var);
24: }
25: if (option == 2)
26: {
27: puts ("\ nEnter a floating point number (e.g. 1.23)");
28:
29: scanf ("% f", & float_var);
30: }
31: if (option == 3)
32: {
33: puts ("\ nEnter an unsigned decimal number \
34: (e.g. 123) ");
35: scanf ("% u", & unsigned_var);
36: }
37: }
38: printf ("\ nYour values ​​are: int:% d float:% f unsigned:% u \ n",
39: int_var, float_var, unsigned_var);
40:
41: return 0;
42: }
43:
44: int menue_option_einlesen (void)
45: {
46: int selection = 0;
47:
48: do
49: {
50: puts ("\ n1 - Read in a signed decimal number");
51: puts ("2 - Read in a floating point number");
52: puts ("3 - Read in an unsigned decimal number");
53: puts ("4 - Leave");
54: puts ("\ nMake a choice:");
55:
56: scanf ("% d", & selection);
57:
58:} while (selection <1 || selection> 4);
59:
60: return selection;
61: }

1 - Read in a signed decimal number
2 - Read in a floating point number
3 - Read in an unsigned decimal number
4 - leave

Make a choice:
1

Enter a signed decimal number (e.g. -123)
-123

1 - Read in a signed decimal number
2 - Read in a floating point number
3 - Read in an unsigned decimal number
4 - leave

Make a choice:
3

Enter an unsigned decimal number (e.g. 123)
321

1 - Read in a signed decimal number
2 - Read in a floating point number
3 - Read in an unsigned decimal number
4 - leave

Make a choice:
2

Enter a floating point number (e.g. 1.23)
1231.123

1 - Read in a signed decimal number
2 - Read in a floating point number
3 - Read in an unsigned decimal number
4 - leave

Make a choice:
4

Their values ​​are: int: -123 float: 1231.123047 unsigned: 321

Listing 6.3 uses the same menu concept as Listing 6.1. The differences in (lines 44 to 61) are minor, but should not be ignored. On the one hand, the function is used instead of. Since no variables are returned, there is no need for. By inserting again the new line characters were removed from lines 51 to 53. Line 58 has also been changed and allows values ​​between 1 and 4 to be entered, as there are now four menu options to choose from. Notice that line 56 has not been changed, but it may make a little more sense now. reads in a decimal value and stores it in the variable. In line 60, the function returns the value of to the calling program.

The listings 6.1 and 6.3 have the same structure. A statement evaluates the return value of. Depending on the value in the variable, the program outputs a message, asks you to enter a number and reads in the value using. Note the difference between lines 23, 29 and 35. Each of these lines reads a variable, but each line expects a different type of variable. The variables of the corresponding types are declared in lines 12 to 14.

When the user selects the menu option to exit, the program outputs the last number entered for each of the three variable types. If the user has not entered a value, it is output because all three types were initialized in lines 12, 13 and 14. One final note on lines 20 through 36. The statements used here are not very well structured. If you are of the opinion that a structure would be more appropriate here, I do not want to contradict you. On day 13, "Working with the screen and keyboard," I will introduce you to another instruction on program flow control. This statement offers an even better solution.

What you should be doing

What not

Use and together with. Use the output functions to request the user to enter values, which are then also read in.

Don't forget the address operator () when using variables.

The scanf () function

#include
scanf (format string [, arguments, ...]);

is a function that conversion specifiers in a given format string use to read values ​​into variable arguments. The addresses of the variables and not the variables themselves must be passed as arguments. In the case of numeric variables, you can transfer the address by placing the address operator () in front of the variable name. The use of requires the integration of the header file.

reads the input fields from the standard input stream, usually the keyboard. It stores each of these read fields in an argument. When storing the information, the function converts the data into the format of the associated specifier of the format string. A conversion specifier must be specified for each argument. Table 6.2 contains the most common conversion specifiers.

example 1

int x, y, z;
scanf ("% d% d% d", & x, & y, & z);

Example 2

#include
int main (void)
{
float y;
int x;
puts ("Enter a floating point number and then an integer");
scanf ("% f% d", & y, & x);
printf ("\ nYour input was% f and% d", y, x);
return 0;
}

Summary

By completing today's lesson, you will have the tools to write your own C programs. The combination of the functions, and and the program control instructions discussed earlier enable you to write simple programs.

The functions and are available for display on the screen. can only output text, while can output both text and variables. Both functions use escape sequences to output control characters and special characters.

The function reads one or more values ​​from the keyboard and interprets them according to the conversion specifiers used. The read-in values ​​are assigned to program variables.

questions and answers

Question:
Why should I use it if it has the same or a greater scope of performance than?

Answer:
Since it can do more, it also has more overhead. If you're trying to write a small, efficient program, or if your programs get very large and resources become increasingly important, take advantage of the low overhead of. In general, you should program as resource-efficiently as possible.

Question:
Why do I have to integrate when I use, or?

Answer:
contains the prototypes for the standard input / output functions. , and are three of these standard functions. Try running a program without the header file and look at the error messages and warnings you inevitably get.

Question:
What happens if I forget the address operator () on a variable?

Answer:
This mistake can happen very easily. And the results are unpredictable. After reading Chapters 9 and 13 and knowing more about pointers, you will understand better. At the moment it is enough to know that if you omit the address operator, the information entered will not be stored in your variable, but in another location in the memory. The consequences range from "apparently without effects" to "program crash with error message". Fortunately, however, you can set the to show all warnings. Then you will be told if you forgot to use the address operator with a call to.

Workshop

The workshop contains quiz questions designed to help you consolidate your knowledge, as well as exercises designed to encourage you to apply what you have learned and gain your own experience. The solutions to the questions and the exercises can be found in Appendix C.

quiz

  1. What is the difference between and?
  2. What is the header file that you have to include when using?
  3. What do the following escape sequences do?
  4. a.
  5. b.
  6. c.
  7. d.
  8. e.
  9. Which conversion specifiers should be used to output the following data?
  10. a. A character string
  11. b. A signed decimal number
  12. c. A floating point number
  13. Using the following examples, what are the differences in the literal text of?
  14. a.
  15. b.
  16. c.
  17. d.

Exercises

Starting today, you will be presented with exercises in which you should write complete programs to solve specific tasks. However, since there is always more than one solution in C, the answers at the end of the book should not be considered the only correct ones. If you set up your own code that does exactly what it was asked for, so much the better! If you have any problems you might find help in the answer. The answers have few comments, as it is good practice to understand the program yourself.

  1. Set up a - and a - statement that start a new line.
  2. Write a statement that reads a character, an unsigned decimal number, and another simple character.
  3. Set up instructions that read in and output an integer.
  4. Modify exercise 3 to only accept even numbers (,, and so on).
  5. Modify exercise 4 so that it reads values ​​until the number 99 or six even numbers have been entered. Save the numbers in an array. (Hint: you need a loop).
  6. Convert exercise 5 into an executable program. Add a function that prints the values ​​in the array on a single line, separated by tabs. (Only output the entered values.)
  7. TROUBLESHOOTING: Find the bug (s) in the following code snippet: printf ("Jack said," Fischers Fritze fishes fresh fish. "");
  8. TROUBLESHOOTING: Find the error (s) in the following program: int hole_1_oder_2 (void)
    {
    int answer = 0;
    while (answer <1 || answer> 2)
    {
    printf (enter 1 for yes, 2 for no);
    scanf ("% f", answer);
    }
    return answer;
    }
  9. Extend the function from Listing 6.1 to display the rest of Table 6.1.
  10. Write a program that reads two floating point numbers from the keyboard and then prints out their product.
  11. Write a program that reads ten integers from the keyboard and then prints the sum of them.
  12. Write a program that reads integers from the keyboard and stores them in an array. Reading should be stopped when a zero has been entered or the end of the array has been reached. Then find and display the largest and smallest values ​​in the array. (Warning: this is not an easy problem because arrays have not yet been fully explored. If you have difficulty doing this, try doing the task again after day 7, "Numeric Arrays".)