- 2.1 Introduction
- 2.2 First Program in C++: Printing a Line of Text
- 2.3 Modifying Our First C++ Program
- 2.4 Another C++ Program: Adding Integers
- 2.5 Memory Concepts
- 2.6 Arithmetic
- 2.7 Decision Making: Equality and Relational Operators
- 2.8 Wrap-Up
- Summary
- Self-Review Exercises
- Answers to Self-Review Exercises
- Exercises
- Making a Difference
2.3 Modifying Our First C++ Program
We now present two examples that modify the program of Fig. 2.1 to print text on one line by using multiple statements and to print text on several lines by using a single statement.
Printing a Single Line of Text with Multiple Statements
Welcome to C++! can be printed several ways. For example, Fig. 2.3 performs stream insertion in multiple statements (lines 8–9), yet produces the same output as the program of Fig. 2.1. [Note: From this point forward, we use a yellow background to highlight the key features each program introduces.] Each stream insertion resumes printing where the previous one stopped. The first stream insertion (line 8) prints Welcome followed by a space, and because this string did not end with \n, the second stream insertion (line 9) begins printing on the same line immediately following the space.
Fig 2.3. Printing a line of text with multiple statements.
1 // Fig. 2.3: fig02_03.cpp 2 // Printing a line of text with multiple statements. 3 #include <iostream> // allows program to output data to the screen 4 5 // function main begins program execution 6 int main() 7 { 8 |
Printing Multiple Lines of Text with a Single Statement
A single statement can print multiple lines by using newline characters, as in line 8 of Fig. 2.4. Each time the \n (newline) escape sequence is encountered in the output stream, the screen cursor is positioned to the beginning of the next line. To get a blank line in your output, place two newline characters back to back, as in line 8.
Fig 2.4. Printing multiple lines of text with a single statement.
1 // Fig. 2.4: fig02_04.cpp
2 // Printing multiple lines of text with a single statement.
3 #include <iostream> // allows program to output data to the screen
4
5 // function main begins program execution
6 int main()
7 {
8 std::cout << "Welcome
|