Chapter 5
Chapter 5
Chapter 5
Control Statements: Part 2
Objectives
• To use for and do…while looping statements
• To implement the switch selection statement
• How break and continue alter the flow of control statements
• To use logical operators to form complex conditional expressions in control
statements
3
initialization;
while ( loop_Continuation_Condition )
{
statement
increment;
}
12
• Vary the control variable from 100 down to 0 in decrements of 1. Notice that we used
type int for the control variable in this for header. The condition does not become false
until control variable i contains -1, so the control variable must be able to store both
positive and negative numbers
for ( int i = 100; i >= 0; --i )
• Vary the control variable over the following sequence of values: 99, 88, 77, 66, 55
for (unsigned int i = 99; i >= 55; i -= 11 )
Example 1
Summing Even Integers from 2 to 20
23
int main()
{
unsigned int sum = 0; // initialize sum
for (unsigned int number = 2; number <= 10; sum += number, number += 2)
; // empty statement
cout << "Sum is " << sum << endl; // output sum
}
25
Example 2
Write a program to calculate the values of a as shown in the formula:
a =(0.8) p
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{ double a;
cout << fixed << setprecision( 2 );
cout << setw( 4 ) << "p" << setw( 21 ) << "a\n" << endl;
} // end for
}
27
• This program will not compile without including header file <cmath>
28
setw() Statement
Using Stream Manipulators to Format Numeric Output
• Parameterized stream manipulators setprecision and setw and the nonparameterized
stream manipulator fixed
• The stream manipulator setw(4) specifies that the next value output should appear in
a field width of 4—i.e., cout prints the value with at least 4 character positions
▫ If less than 4 character positions wide, the value is right justified in the field by default
• To indicate that values should be output left justified, simply output nonparameterized
stream manipulator << left <<
• Right justification can be restored by outputting nonparameterized stream manipulator
<< right <<
29
setprecision Statement
• Stream manipulator fixed indicates that floating-point values should be
output as fixed-point values with decimal points
• Stream manipulator setprecision specifies the number of digits to
the right of the decimal point
• Stream manipulators fixed and setprecision remain in effect until
they’re changed—such settings are called sticky settings
• The field width specified with setw applies only to the next value output
30
for vs while
What is the output of the code on the left? Re-write the code using the
for statement to show the same result.
Using FOR statement:
#include <iostream>
using namespace std; #include <iostream>
int main () using namespace std;
{ int main ()
int k, sum; {
sum = k = 0; OUTPUT: 5 10 int k, sum;
while (k < 5) { sum = 0;
sum += k; for (k=0; k < 5;k++) {
++k; sum += k;
} }
cout << k << " " << sum << endl; cout << k << " "<< sum << endl;
} }
31
Exercise: Use the switch statement to count how many times a user
entered the letters ‘A’ and ‘B’
#include <iostream>
using namespace std;
int main()
{
int grade; // one grade
unsigned int aCount = 0; // number of As
unsigned int bCount = 0; // number of Bs
cout << "Enter the letter grades" << endl;
cout << "Enter the EOF character to end input" << endl;
42
// loop until user types end-of-file key case '\n': // ignore newlines,
sequence case '\t': // tabs
while ( ( grade = cin.get() ) != EOF ) { case ' ': // and spaces in input
switch ( grade ) { break; // exit switch
case 'A': // grade was uppercase A
case 'a': // or lowercase a default: // catch all other characters
++aCount; // increment aCount cout << "Incorrect letter grade
break; // necessary to exit switch entered." <<endl ;
cout << " Enter a new grade." << endl;
case 'B': // grade was uppercase B break;
case 'b': // or lowercase b } // end switch
++bCount; // increment bCount } // end while
break; // exit switch
43
if ( x == 5 ) {
break; // break loop only if x is 5 The code prints the
} // end if numbers from 1 to 4
cout << x << endl; // display value of x
because the break
} // end for statement exits the
cout << "Broke out of loop at x = " << x << endl; loop when x equals 5
} // end function main
55
if ( x == 5 ) {
continue; // break loop only if x is 5
} // end if The code prints the
numbers from 1 to 10
cout << x << endl; // display value of x
} // end for
but skips printing the
cout << “Number 5 is skipped" << endl; number 5
} // end function main
57
Logical Operators
• C++ provides logical operators that are used to form more complex
conditions by combining simple conditions
• The logical operators are && (logical AND), || (logical OR) and ! (logical
NOT, also called logical negation)
58
Logical Operators
Logical AND (&&) Operator
• The && (logical AND) operator is used to ensure that two conditions are both true
before we choose a certain path of execution
• The simple condition to the left of the && operator evaluates first
• The simple condition to the right of the && operator evaluates next
• The right side of a logical AND expression is evaluated only if the left side is true
Logical Operators
Logical OR (||) Operator
• The || (logical OR) operator determines if either or both of two conditions are true
before we choose a certain path of execution
• The && operator has a higher precedence than the || operator
• Both operators associate from left to right
Logical Operators
Logical Negation (!) Operator
• C++ provides the ! (logical NOT, also called logical negation) operator to “reverse” a
condition’s meaning
• The unary logical negation operator has only a single condition as an operand
• You can often avoid the ! operator by using an appropriate relational or equality
operator
if ( !( grade == sentinelValue ) )
cout << "The next grade is “ << grade << endl; OR ..
if ( grade != sentinelValue )
cout << "The next grade is “ << grade << endl;
63
Logical Operators
Logical Operators Example
• The following program demonstrates the logical operators by producing
their truth tables
• The output shows each expression that is evaluated and its bool result
• By default, bool values true and false are displayed by cout and the
stream insertion operator as 1 and 0, respectively
• Stream manipulator boolalpha (a sticky manipulator) specifies that the
value of each bool expression should be displayed as either the word
“true” or the word “false”
65
66
Exercises
68
Exercise 1
Write a program that uses for statement to print the following shape.
*
** #include <iostream>
*** using namespace std;
****
***** int main()
{
for (int i=1;i<=5;i++)
{
for (int j=1;j<=i;j++)
{cout << "*";}
Exercise 2
What is the output?
#include <iostream>
using namespace std;
int main ()
{ for ( int i = 1; i <= 5; ++i )
{
for ( int j = 1; j <= 3; ++j )
{
for ( int k = 1; k <= 4; ++k )
cout << '*';
cout << endl;
} // end inner for
cout << endl;
} // end outer for
}
70
Exercise 3
What is the output? for ( int i = 1; i <= y; ++i ) // count from 1 to y
{
for ( int j = 1; j <= x; ++j )
#include <iostream>
cout << '@'; // output @
using namespace std;
Exercise 4
Find the error(s), if any, in each of the following: c) The following code should output the odd integers from 19
a) for ( x = 100, x >= 1, ++x ) to 1:
cout << x << endl; for ( x = 19; x >= 1; x += 2 )
cout << x << endl;
Exercise 5
Write a program that uses a for statement to calculate and print the sum of the odd
integers from 1 to 6
#include <iostream>
using namespace std;
int main()
{
int sum=0; OUTPUT:
for (int i=1; i<=6; i++) 9
{ Now, write another
if ( (i % 2) != 0) program to calculate and
{sum = sum + i ;}
} print the product of odd
cout << "The sum of odd numbers is " << sum << endl; numbers from 1 to 6
} // end main In this case the result
should be 15