Section 1-4 Basic Flow of Control
The while
Statement
Basic Structure
while (condition)
statement
Rule for while
The body part(statement part) will be executed repeatedly until the condition turns into false.
Exercises
Exercise 1-9
Write a program that uses a while
to sum the numbers from 50 to 100.
Solution
In 1-9.cpp
Exercise 1-10
In addition to the ++
operator that adds 1
to its operand, there is a decrement operator (--
) that subtracts 1
. Use the decrement operator to write a while
that prints the numbers from ten down to zero.
Solution
In 1-10.cpp
Exercise 1-11
Write a program that prompts the user for two integers. Print each number in the range specified by those two integers.
Solution
In 1-11.cpp
Example Code
In WhileStatement.cpp
The for
Statement
Basic Structure
for (init; cond; incre(statement))
statement;
init for initialization; run the body statement until the cond is false; incre usually alternates the variable to make the cond false and the program terminate.
Main Purpose
Describe the fixed pattern of iteration.
Exercises
Exercise 1-12
What does the following for
loop do? What is the final value of sum
?
int sum = 0;
for (int i = -100; i <= 100; ++i)
sum += i;
Solution
Calculate the sum from -100 to 100, which is 0.
Exercise 1-13
Rewrite the exercises from 1.4.1 using for
loop.
Solution
In 1-13-1-9.cpp
, 1-13-1-10.cpp
and 1-13-1-11.cpp
Exercise 1-14
Compare and contrast the loops that used a for
with those using a while
. Are there advantages or disadvantages to using either form?
Solution
for
statement is clearer. However, the while
statement can be more flexible. Although these two patterns are equivalent, using the alternative in the situation suited for the other will be confusing.
Exercise 1-15
Write programs that contain the common errors discussed in the box on page 16.
Familiarize yourself with the messages the compiler generates.
Solution
// error: missing ) in parameter list for main
int main ( {
// error: used colon, not a semicolon, after all
std::cout << "Read each file." << std::endl:
// error: missing quotes around string literal
std::cout << Update master. << std::endl;
// error: second output operator is missing
std::cout << "Write new master." std::endl;
// error: missing; on return statement
return 0
}
will generate the compiler messages:
int main ( {
^
1-15-1.cpp:6:48: error: found ‘:’ in nested-name-specifier, expected ‘::’
std::cout << “Read each file.” << std::endl:
^
1-15-1.cpp:6:44: error: ‘std::endl’ is not a class or namespace
std::cout << “Read each file.” << std::endl:
^
1-15-1.cpp:8:18: error: ‘Update’ was not declared in this scope
std::cout << Update master. << std::endl;
^
1-15-1.cpp:8:25: error: expected ‘}’ before ‘master’
std::cout << Update master. << std::endl;
^
1-15-1.cpp:8:25: error: expected ‘)’ before ‘master’
1-15-1.cpp:10:10: error: ‘cout’ in namespace ‘std’ does not name a type
std::cout << “Write new master.” std::endl;
^
1-15-1.cpp:12:5: error: expected unqualified-id before ‘return’
return 0
^
1-15-1.cpp:13:1: error: expected declaration before ‘}’ token
}
^
#include<iostream>
int main()
{
int v1 = 0, v2 = 0;
std::cin >> v >> v2; // error: uses "v" not "v1"
// error: cout not defined; should be std::cout
cout << v1 + v2 << std::endl;
return 0;
}
will generate the compiler messages:
1-15-2.cpp: In function ‘int main()’:
1-15-2.cpp:5:17: error: ‘v’ was not declared in this scope
std::cin >> v >> v2; // error: uses “v” not “v1”
^
1-15-2.cpp:7:5: error: ‘cout’ was not declared in this scope
cout << v1 + v2 << std::endl;
^
1-15-2.cpp:7:5: note: suggested alternative:
In file included from 1-15-2.cpp:1:0:
/usr/include/c++/5/iostream:61:18: note: ‘std::cout’
extern ostream cout; /// Linked to standard output
^
Example Code
In ForStatement.cpp
Read Unknown Number of numbers from input
Since we have learned about while
and for
statements, we can explore this topic.
Both of the statements can fulfill the purpose.
Key to success is the return value of cin
. When tested, the return value will be true as long as the read-in value is legal. If the read-in value does not suit the type of the variable or turns out to be EOF(End Of File), the return value will be false.
Exercise
Exercise 1-16
Write your own version of a program that prints the sum of a set of integers read from cin
.
Solution
In 1-16.cpp
, I use for
statement instead of while
statement in the example.
Example Code
In ReadUntilEOF.cpp
Enter EOF From Your Keyboard
On Windows, enter ctrl+z
. On Max OS X or Linux, enter ctrl+d
.
if
Statement
Basic Structure
if (cond0)
statement0;
else if (cond1)
statement1;
...
else if (condn)
statementn;
else
statement;
Rules for if
Statement
- Whenever the condition is true, the corresponding statement will be executed.
- If all the conditions are false, the
else
-part will be executed. - All the parts except the first cond0 can be omitted. And once a part is omitted, they will not be executed. So there is a chance that the
if
statement does nothing.
Exercises
Exercise 1-17
What happens in the program(IfStatement.cpp
) presented in this section if the input values are all equal? What if there are no duplicated values?
Solution
In Both situations, this program will work well and give correct answer.
But in the first situation, with all values equal, the else
-part of if
statement will never be executed. Correspondingly, in the second situation, with all values distinct, the if
-part of if
statement will never be executed.
Exercises 1-18
Compile and run the program from this section giving it only equal values as input. Run it again giving it values in which no number is repeated.
Solution
Give the identical input:
1 1 1 1 1 1 1
Corresponding output:
1 occurs 7 times
Give the distinct input:
1 2 3 4 5 6 7
Corresponding output:
1 occurs 1 times
2 occurs 1 times
3 occurs 1 times
4 occurs 1 times
5 occurs 1 times
6 occurs 1 times
7 occurs 1 times
Exercises 1-19
Revise the program you wrote for the exercises in 1.4.1 that printed a range of numbers so that it handles input in which the first number is smaller than the second.
Solution
When I wrote it for the first time in 1-11.cpp
and 1-13-1-11.cpp
, I designed it to be able to handle this situation.
Common Errors Presented by Compilers
- Syntax Errors
- Type Errors
Assigning a value of wrong type to a variable - Declaration Errors
Using a variable before declaring it or mistakenly spelling an identifier