SlideShare a Scribd company logo
Control Structures in C++
while, do/while, for
switch, break, continue
The while Repetition Structure
• Repetition structure
– Programmer specifies an action to be repeated while
some condition remains true
– Psuedocode
while there are more items on my shopping list
Purchase next item and cross it off my list
– while loop repeated until condition becomes false.
• Example
int product = 2;
while ( product <= 1000 )
product = 2 * product;
• Flowchart of while loop
condition statement
true
false
The while Repetition Structure
int x = 2;
while (x >= 0){
if ( x == 2){
cout << “Value of x is : “ << x << endl;
}
x = x – 1;
}
• Common errors:
– infinite loop
– unitialized variables
There are functions that return True or False :
cin.eof()
So..
char s;
while (!cin.eof( )) {
cin >> s;
cout << s << endl;
}
Formulating Algorithms (Counter-
Controlled Repetition)
• Counter-controlled repetition
– Loop repeated until counter reaches a certain value.
• Definite repetition
– Number of repetitions is known
• Example
A class of ten students took a quiz. The grades (integers
in the range 0 to 100) for this quiz are available to you.
Determine the class average on the quiz.
Formulating Algorithms (Counter-
Controlled Repetition)
• Pseudocode for example:
Set total and grade counter to zero
While grade counter <= 10
Input the next grade
Add the grade into the total
grade counter++
average = total divided / 10
Print the class average
• Following is the C++ code for this example
1 // Fig. 2.7: fig02_07.cpp
2 // Class average program with counter-controlled repetition
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10 {
11 int total, // sum of grades
12 gradeCounter, // number of grades entered
13 grade, // one grade
14 average; // average of grades
15
16 // initialization phase
17 total = 0; // clear total
18 gradeCounter = 1; // prepare to loop
19
20 // processing phase
21 while ( gradeCounter <= 10 ) { // loop 10 times
22 cout << "Enter grade: "; // prompt for input
23 cin >> grade; // input grade
24 total = total + grade; // add grade to total
25 gradeCounter = gradeCounter + 1; // increment counter
26 }
27
28 // termination phase
29 average = total / 10; // integer division
30 cout << "Class average is " << average << endl;
31
32 return 0; // indicate program ended successfully
33 }
The counter gets incremented each time
the loop executes. Eventually, the
counter causes the loop to end.
Program Output
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
Assignment Operators
• Assignment expression abbreviations
c = c + 3; can be abbreviated as c += 3; using the
addition assignment operator
• Statements of the form
variable = variable operator expression;
can be rewritten as
variable operator= expression;
• Examples of other assignment operators include:
d -= 4 (d = d - 4)
e *= 5 (e = e * 5)
f /= 3 (f = f / 3)
g %= 9 (g = g % 9)
Increment and Decrement Operators
• Increment operator (c++) - can be used instead of
c += 1
• Decrement operator (c--) - can be used instead of
c -= 1
• Preincrement
• When the operator is used before the variable (++c or –c)
• Variable is changed, then the expression it is in is evaluated.
• Posincrement
• When the operator is used after the variable (c++ or c--)
• Expression the variable is in executes, then the variable is changed.
• If c = 5, then
– cout << ++c; prints out 6 (c is changed
before cout is executed)
– cout << c++; prints out 5 (cout is
executed before the increment. c now has the
value of 6)
• When Variable is not in an expression
– Preincrementing and postincrementing have the
same effect.
++c;
cout << c;
and
c++;
cout << c;
have the same effect.
Essentials of Counter-Controlled
Repetition
• Counter-controlled repetition requires:
– The name of a control variable (or loop counter).
– The initial value of the control variable.
– The condition that tests for the final value of the control variable (i.e.,
whether looping should continue).
– The increment (or decrement) by which the control variable is modified
each time through the loop.
• Example:
int counter =1; //initialization
while (counter <= 10){ //repetitio
// condition
cout << counter << endl;
++counter; //increment
}
The for Repetition Structure
• The general format when using for loops is
for ( initialization; LoopContinuationTest;
increment )
statement
• Example:
for( int counter = 1; counter <= 10;
counter++ )
cout << counter << endl;
– Prints the integers from one to ten
• For loops can usually be rewritten as while
loops:
initialization;
while ( loopContinuationTest){
statement
increment;
}
• Initialization and increment as comma-
separated lists
for (int i = 0, j = 0; j + i <= 10; j+
+, i++)
cout << j + i << endl;
Flowchart for for
Condition
Test the variable
statement
true
false
Increment variable
Initialize variable
1 // Fig. 2.20: fig02_20.cpp
2 // Summation with for
3 #include <iostream>
4
5 using std::cout;
6 using std::endl;
7
8 int main()
9 {
10 int sum = 0;
11
12 for ( int number = 2; number <= 100; number += 2 )
13 sum += number;
14
15 cout << "Sum is " << sum << endl;
16
17 return 0;
18 }
Sum is 2550
• Program to sum the even numbers from 2 to 100
The switch Multiple-Selection Structure
• switch
– Useful when variable or expression is tested for
multiple values
– Consists of a series of case labels and an optional
default case
– break is (almost always) necessary
switch (expression) {
case val1:
statement
break;
case val2:
statement
break;
….
case valn:
statement
break;
default:
statement
break;
}
if (expression == val1)
statement
else if (expression==val2)
statement
….
else if (expression== valn)
statement
else
statement
flowchart
true
false
.
.
.
case a case a action(s) break
case b case b action(s) break
false
false
case z case z action(s) break
true
true
default action(s)
1 // Fig. 2.22: fig02_22.cpp
2 // Counting letter grades
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10 {
11 int grade, // one grade
12 aCount = 0, // number of A's
13 bCount = 0, // number of B's
14 cCount = 0, // number of C's
15 dCount = 0, // number of D's
16 fCount = 0; // number of F's
17
18 cout << "Enter the letter grades." << endl
19 << "Enter the EOF character to end input." << endl;
20
21 while ( ( grade = cin.get() ) != EOF ) {
22
23 switch ( grade ) { // switch nested in while
24
25 case 'A': // grade was uppercase A
26 case 'a': // or lowercase a
27 ++aCount;
28 break; // necessary to exit switch
29
30 case 'B': // grade was uppercase B
31 case 'b': // or lowercase b
32 ++bCount;
33 break;
34
Notice how the case statement is used
35 case 'C': // grade was uppercase C
36 case 'c': // or lowercase c
37 ++cCount;
38 break;
39
40 case 'D': // grade was uppercase D
41 case 'd': // or lowercase d
42 ++dCount;
43 break;
44
45 case 'F': // grade was uppercase F
46 case 'f': // or lowercase f
47 ++fCount;
48 break;
49
50 case 'n': // ignore newlines,
51 case 't': // tabs,
52 case ' ': // and spaces in input
53 break;
54
55 default: // catch all other characters
56 cout << "Incorrect letter grade entered."
57 << " Enter a new grade." << endl;
58 break; // optional
59 }
60 }
61
62 cout << "nnTotals for each letter grade are:"
63 << "nA: " << aCount
64 << "nB: " << bCount
65 << "nC: " << cCount
66 << "nD: " << dCount
67 << "nF: " << fCount << endl;
68
69 return 0;
break causes switch to end and
the program continues with the first
statement after the switch structure.
Notice the default statement.
Program Output
Enter the letter grades.
Enter the EOF character to end input.
a
B
c
C
A
d
f
C
E
Incorrect letter grade entered. Enter a new grade.
D
A
b
Totals for each letter grade are:
A: 3
B: 2
C: 3
D: 2
F: 1
The do/while Repetition Structure
• The do/while repetition structure is similar to the
while structure,
– Condition for repetition tested after the body of the loop is
executed
• Format:
do {
statement
} while ( condition );
• Example (letting counter = 1):
do {
cout << counter << " ";
} while (++counter <= 10);
– This prints the integers from 1 to 10
• All actions are performed at least once.
true
false
statement
condition
The break and continue Statements
• Break
– Causes immediate exit from a while, for,
do/while or switch structure
– Program execution continues with the first
statement after the structure
– Common uses of the break statement:
• Escape early from a loop
• Skip the remainder of a switch structure
• Continue
– Skips the remaining statements in the body of a
while, for or do/while structure and proceeds
with the next iteration of the loop
– In while and do/while, the loop-continuation test
is evaluated immediately after the continue
statement is executed
– In the for structure, the increment expression is
executed, then the loop-continuation test is evaluated
The continue Statement
• Causes an immediate jump to the loop test
int next = 0;
while (true){
cin >> next;
if (next < 0)
break;
if (next % 2) //odd number, don’t print
continue;
cout << next << endl;
}
cout << “negative num so here we are!” << endl;
Sentinel-Controlled Repetition
• Suppose the previous problem becomes:
Develop a class-averaging program that will process
an arbitrary number of grades each time the program
is run.
– Unknown number of students - how will the program
know to end?
• Sentinel value
– Indicates “end of data entry”
– Loop ends when sentinel inputted
– Sentinel value chosen so it cannot be confused with a
regular input (such as -1 in this case)
• Top-down, stepwise refinement
– begin with a pseudocode representation of the
top:
Determine the class average for the quiz
– Divide top into smaller tasks and list them in
order:
Initialize variables
Input, sum and count the quiz grades
Calculate and print the class average
Input, sum and count the quiz grades
to
Input the first grade (possibly the sentinel)
While the user has not as yet entered the sentinel
Add this grade into the running total
Add one to the grade counter
Input the next grade (possibly the sentinel)
• Refine
Calculate and print the class average
to
If the counter is not equal to zero
Set the average to the total divided by the counter
Print the average
Else
Print “No grades were entered”
1 // Fig. 2.9: fig02_09.cpp
2 // Class average program with sentinel-controlled repetition.
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8 using std::ios;
9
10 #include <iomanip>
11
12 using std::setprecision;
13 using std::setiosflags;
14
15 int main()
16 {
17 int total, // sum of grades
18 gradeCounter, // number of grades entered
19 grade; // one grade
20 double average; // number with decimal point for average
21
22 // initialization phase
23 total = 0;
24 gradeCounter = 0;
25
26 // processing phase
27 cout << "Enter grade, -1 to end: ";
28 cin >> grade;
29
30 while ( grade != -1 ) {
Data type double used to represent
decimal numbers.
31 total = total + grade;
32 gradeCounter = gradeCounter + 1;
33 cout << "Enter grade, -1 to end: ";
34 cin >> grade;
35 }
36
37 // termination phase
38 if ( gradeCounter != 0 ) {
39 average = static_cast< double >( total ) / gradeCounter;
40 cout << "Class average is " << setprecision( 2 )
41 << setiosflags( ios::fixed | ios::showpoint )
42 << average << endl;
43 }
44 else
45 cout << "No grades were entered" << endl;
46
47 return 0; // indicate program ended successfully
48 }
Enter grade, -1 to end: 75
Enter grade, -1 to end: 94
Enter grade, -1 to end: 97
Enter grade, -1 to end: 88
Enter grade, -1 to end: 70
Enter grade, -1 to end: 64
Enter grade, -1 to end: 83
Enter grade, -1 to end: 89
Enter grade, -1 to end: -1
Class average is 82.50
setiosflags(ios::fixed | ios::showpoint) - stream
manipulator
ios::fixed - output numbers with a fixed number of decimal
points.
ios::showpoint - forces decimal point and trailing zeros, even if
unnecessary: 66 printed as 66.00
| - separates multiple option.
setprecision(2) - prints only two digits
past decimal point.
Programs that use this must include <iomanip>
static_cast<double>() - treats total as a
double temporarily.
Required because dividing two integers truncates the
remainder.
gradeCounter is an int, but it gets promoted to
double.
Nested control structures
• Problem:
A college has a list of test results (1 = pass, 2 = fail) for 10
students. Write a program that analyzes the results. If more
than 8 students pass, print "Raise Tuition".
• We can see that
– The program must process 10 test results. A counter-
controlled loop will be used.
– Two counters can be used—one to count the number of
students who passed the exam and one to count the number of
students who failed the exam.
– Each test result is a number—either a 1 or a 2. If the number
is not a 1, we assume that it is a 2.
Nested control structures
• High level description of the algorithm
Initialize variables
Input the ten quiz grades and count passes and failur
Print a summary of the exam results and decide if
tuition should be raised
1 // Fig. 2.11: fig02_11.cpp
2 // Analysis of examination results
3 #include <iostream>
4
5 using std::cout;
6 using std::cin;
7 using std::endl;
8
9 int main()
10 {
11 // initialize variables in declarations
12 int passes = 0, // number of passes
13 failures = 0, // number of failures
14 studentCounter = 1, // student counter
15 result; // one exam result
16
17 // process 10 students; counter-controlled loop
18 while ( studentCounter <= 10 ) {
19 cout << "Enter result (1=pass,2=fail): ";
20 cin >> result;
21
22 if ( result == 1 ) // if/else nested in while
23 passes = passes + 1;
3. Print results
24 else
25 failures = failures + 1;
26
27 studentCounter = studentCounter + 1;
28 }
29
30 // termination phase
31 cout << "Passed " << passes << endl;
32 cout << "Failed " << failures << endl;
33
34 if ( passes > 8 )
35 cout << "Raise tuition " << endl;
36
37 return 0; // successful termination
38 }
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 2
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Enter result (1=pass,2=fail): 1
Passed 9
Failed 1
Raise tuition
// Fig. 2.21: fig02_21.cpp
// Calculating compound interest
#include <iostream>
using std::cout;
using std::endl;
using std::ios;
#include <iomanip>
using std::setw;
using std::setiosflags;
using std::setprecision;
#include <cmath>
int main()
{
double amount, // amount on deposit
principal = 1000.0, // starting principal
rate = .05; // interest rate
cout << "Year" << setw( 21 )
<< "Amount on deposit" << endl;
// set the floating-point number format
cout << setiosflags( ios::fixed | ios::showpoint )
<< setprecision( 2 );
for ( int year = 1; year <= 10; year++ ) {
amount = principal * pow( 1.0 + rate, year );
cout << setw( 4 ) << year << setw( 21 ) << amount
<< endl;
}
return 0;
}

More Related Content

PPT
Control Statement.ppt
PPT
Chapter 3 Control structures.ppt
PPT
Control structures.ppt
PPTX
control statements of clangauge (ii unit)
PPTX
SwitchandlomahsjhASSJjajdjsdjdjjjop.pptx
PPTX
control structure
PPT
Lecture#3 Algorithms and computing
PPT
03b loops
Control Statement.ppt
Chapter 3 Control structures.ppt
Control structures.ppt
control statements of clangauge (ii unit)
SwitchandlomahsjhASSJjajdjsdjdjjjop.pptx
control structure
Lecture#3 Algorithms and computing
03b loops

Similar to for loops in C++ and their functions and applicability (20)

PPTX
Control Structures in C
PDF
4th_Ed_Ch03.pdf
PPTX
Iterative control structures, looping, types of loops, loop working
PDF
PROBLEM SOLVING USING NOW PPSC- UNIT -2.pdf
PPT
cpphtp4_PPT_02.ppt
PPT
Iteration
PPTX
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...
PPT
Lecture#5 Operators in C++
PPTX
Control Structures.pptx
PPT
Verilog Lecture3 hust 2014
PPTX
Cs1123 6 loops
PPT
FP 201 - Unit 3 Part 2
PPT
Chapter 5 Looping
PPTX
Object oriented programming system with C++
PPT
Csphtp1 05
PPT
03 conditions loops
PDF
Loop and while Loop
PPT
Visula C# Programming Lecture 3
PPT
C++ control loops
PPTX
Managing input and output operations & Decision making and branching and looping
Control Structures in C
4th_Ed_Ch03.pdf
Iterative control structures, looping, types of loops, loop working
PROBLEM SOLVING USING NOW PPSC- UNIT -2.pdf
cpphtp4_PPT_02.ppt
Iteration
Metode Perancangan Program #2 Selection and Repetition Control Structure-ITSB...
Lecture#5 Operators in C++
Control Structures.pptx
Verilog Lecture3 hust 2014
Cs1123 6 loops
FP 201 - Unit 3 Part 2
Chapter 5 Looping
Object oriented programming system with C++
Csphtp1 05
03 conditions loops
Loop and while Loop
Visula C# Programming Lecture 3
C++ control loops
Managing input and output operations & Decision making and branching and looping
Ad

Recently uploaded (20)

PDF
Anesthesia in Laparoscopic Surgery in India
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Cell Types and Its function , kingdom of life
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
master seminar digital applications in india
PPTX
GDM (1) (1).pptx small presentation for students
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
01-Introduction-to-Information-Management.pdf
PDF
Pre independence Education in Inndia.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
Final Presentation General Medicine 03-08-2024.pptx
Anesthesia in Laparoscopic Surgery in India
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Cell Types and Its function , kingdom of life
human mycosis Human fungal infections are called human mycosis..pptx
master seminar digital applications in india
GDM (1) (1).pptx small presentation for students
Renaissance Architecture: A Journey from Faith to Humanism
01-Introduction-to-Information-Management.pdf
Pre independence Education in Inndia.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Basic Mud Logging Guide for educational purpose
O7-L3 Supply Chain Operations - ICLT Program
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
RMMM.pdf make it easy to upload and study
Final Presentation General Medicine 03-08-2024.pptx
Ad

for loops in C++ and their functions and applicability

  • 1. Control Structures in C++ while, do/while, for switch, break, continue
  • 2. The while Repetition Structure • Repetition structure – Programmer specifies an action to be repeated while some condition remains true – Psuedocode while there are more items on my shopping list Purchase next item and cross it off my list – while loop repeated until condition becomes false. • Example int product = 2; while ( product <= 1000 ) product = 2 * product;
  • 3. • Flowchart of while loop condition statement true false The while Repetition Structure int x = 2; while (x >= 0){ if ( x == 2){ cout << “Value of x is : “ << x << endl; } x = x – 1; }
  • 4. • Common errors: – infinite loop – unitialized variables There are functions that return True or False : cin.eof() So.. char s; while (!cin.eof( )) { cin >> s; cout << s << endl; }
  • 5. Formulating Algorithms (Counter- Controlled Repetition) • Counter-controlled repetition – Loop repeated until counter reaches a certain value. • Definite repetition – Number of repetitions is known • Example A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz.
  • 6. Formulating Algorithms (Counter- Controlled Repetition) • Pseudocode for example: Set total and grade counter to zero While grade counter <= 10 Input the next grade Add the grade into the total grade counter++ average = total divided / 10 Print the class average • Following is the C++ code for this example
  • 7. 1 // Fig. 2.7: fig02_07.cpp 2 // Class average program with counter-controlled repetition 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 int main() 10 { 11 int total, // sum of grades 12 gradeCounter, // number of grades entered 13 grade, // one grade 14 average; // average of grades 15 16 // initialization phase 17 total = 0; // clear total 18 gradeCounter = 1; // prepare to loop 19 20 // processing phase 21 while ( gradeCounter <= 10 ) { // loop 10 times 22 cout << "Enter grade: "; // prompt for input 23 cin >> grade; // input grade 24 total = total + grade; // add grade to total 25 gradeCounter = gradeCounter + 1; // increment counter 26 } 27 28 // termination phase 29 average = total / 10; // integer division 30 cout << "Class average is " << average << endl; 31 32 return 0; // indicate program ended successfully 33 } The counter gets incremented each time the loop executes. Eventually, the counter causes the loop to end.
  • 8. Program Output Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81
  • 9. Assignment Operators • Assignment expression abbreviations c = c + 3; can be abbreviated as c += 3; using the addition assignment operator • Statements of the form variable = variable operator expression; can be rewritten as variable operator= expression; • Examples of other assignment operators include: d -= 4 (d = d - 4) e *= 5 (e = e * 5) f /= 3 (f = f / 3) g %= 9 (g = g % 9)
  • 10. Increment and Decrement Operators • Increment operator (c++) - can be used instead of c += 1 • Decrement operator (c--) - can be used instead of c -= 1 • Preincrement • When the operator is used before the variable (++c or –c) • Variable is changed, then the expression it is in is evaluated. • Posincrement • When the operator is used after the variable (c++ or c--) • Expression the variable is in executes, then the variable is changed.
  • 11. • If c = 5, then – cout << ++c; prints out 6 (c is changed before cout is executed) – cout << c++; prints out 5 (cout is executed before the increment. c now has the value of 6)
  • 12. • When Variable is not in an expression – Preincrementing and postincrementing have the same effect. ++c; cout << c; and c++; cout << c; have the same effect.
  • 13. Essentials of Counter-Controlled Repetition • Counter-controlled repetition requires: – The name of a control variable (or loop counter). – The initial value of the control variable. – The condition that tests for the final value of the control variable (i.e., whether looping should continue). – The increment (or decrement) by which the control variable is modified each time through the loop. • Example: int counter =1; //initialization while (counter <= 10){ //repetitio // condition cout << counter << endl; ++counter; //increment }
  • 14. The for Repetition Structure • The general format when using for loops is for ( initialization; LoopContinuationTest; increment ) statement • Example: for( int counter = 1; counter <= 10; counter++ ) cout << counter << endl; – Prints the integers from one to ten
  • 15. • For loops can usually be rewritten as while loops: initialization; while ( loopContinuationTest){ statement increment; } • Initialization and increment as comma- separated lists for (int i = 0, j = 0; j + i <= 10; j+ +, i++) cout << j + i << endl;
  • 16. Flowchart for for Condition Test the variable statement true false Increment variable Initialize variable
  • 17. 1 // Fig. 2.20: fig02_20.cpp 2 // Summation with for 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 int main() 9 { 10 int sum = 0; 11 12 for ( int number = 2; number <= 100; number += 2 ) 13 sum += number; 14 15 cout << "Sum is " << sum << endl; 16 17 return 0; 18 } Sum is 2550 • Program to sum the even numbers from 2 to 100
  • 18. The switch Multiple-Selection Structure • switch – Useful when variable or expression is tested for multiple values – Consists of a series of case labels and an optional default case – break is (almost always) necessary
  • 19. switch (expression) { case val1: statement break; case val2: statement break; …. case valn: statement break; default: statement break; } if (expression == val1) statement else if (expression==val2) statement …. else if (expression== valn) statement else statement
  • 20. flowchart true false . . . case a case a action(s) break case b case b action(s) break false false case z case z action(s) break true true default action(s)
  • 21. 1 // Fig. 2.22: fig02_22.cpp 2 // Counting letter grades 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 int main() 10 { 11 int grade, // one grade 12 aCount = 0, // number of A's 13 bCount = 0, // number of B's 14 cCount = 0, // number of C's 15 dCount = 0, // number of D's 16 fCount = 0; // number of F's 17 18 cout << "Enter the letter grades." << endl 19 << "Enter the EOF character to end input." << endl; 20 21 while ( ( grade = cin.get() ) != EOF ) { 22 23 switch ( grade ) { // switch nested in while 24 25 case 'A': // grade was uppercase A 26 case 'a': // or lowercase a 27 ++aCount; 28 break; // necessary to exit switch 29 30 case 'B': // grade was uppercase B 31 case 'b': // or lowercase b 32 ++bCount; 33 break; 34 Notice how the case statement is used
  • 22. 35 case 'C': // grade was uppercase C 36 case 'c': // or lowercase c 37 ++cCount; 38 break; 39 40 case 'D': // grade was uppercase D 41 case 'd': // or lowercase d 42 ++dCount; 43 break; 44 45 case 'F': // grade was uppercase F 46 case 'f': // or lowercase f 47 ++fCount; 48 break; 49 50 case 'n': // ignore newlines, 51 case 't': // tabs, 52 case ' ': // and spaces in input 53 break; 54 55 default: // catch all other characters 56 cout << "Incorrect letter grade entered." 57 << " Enter a new grade." << endl; 58 break; // optional 59 } 60 } 61 62 cout << "nnTotals for each letter grade are:" 63 << "nA: " << aCount 64 << "nB: " << bCount 65 << "nC: " << cCount 66 << "nD: " << dCount 67 << "nF: " << fCount << endl; 68 69 return 0; break causes switch to end and the program continues with the first statement after the switch structure. Notice the default statement.
  • 23. Program Output Enter the letter grades. Enter the EOF character to end input. a B c C A d f C E Incorrect letter grade entered. Enter a new grade. D A b Totals for each letter grade are: A: 3 B: 2 C: 3 D: 2 F: 1
  • 24. The do/while Repetition Structure • The do/while repetition structure is similar to the while structure, – Condition for repetition tested after the body of the loop is executed • Format: do { statement } while ( condition ); • Example (letting counter = 1): do { cout << counter << " "; } while (++counter <= 10); – This prints the integers from 1 to 10 • All actions are performed at least once. true false statement condition
  • 25. The break and continue Statements • Break – Causes immediate exit from a while, for, do/while or switch structure – Program execution continues with the first statement after the structure – Common uses of the break statement: • Escape early from a loop • Skip the remainder of a switch structure
  • 26. • Continue – Skips the remaining statements in the body of a while, for or do/while structure and proceeds with the next iteration of the loop – In while and do/while, the loop-continuation test is evaluated immediately after the continue statement is executed – In the for structure, the increment expression is executed, then the loop-continuation test is evaluated
  • 27. The continue Statement • Causes an immediate jump to the loop test int next = 0; while (true){ cin >> next; if (next < 0) break; if (next % 2) //odd number, don’t print continue; cout << next << endl; } cout << “negative num so here we are!” << endl;
  • 28. Sentinel-Controlled Repetition • Suppose the previous problem becomes: Develop a class-averaging program that will process an arbitrary number of grades each time the program is run. – Unknown number of students - how will the program know to end? • Sentinel value – Indicates “end of data entry” – Loop ends when sentinel inputted – Sentinel value chosen so it cannot be confused with a regular input (such as -1 in this case)
  • 29. • Top-down, stepwise refinement – begin with a pseudocode representation of the top: Determine the class average for the quiz – Divide top into smaller tasks and list them in order: Initialize variables Input, sum and count the quiz grades Calculate and print the class average
  • 30. Input, sum and count the quiz grades to Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) • Refine Calculate and print the class average to If the counter is not equal to zero Set the average to the total divided by the counter Print the average Else Print “No grades were entered”
  • 31. 1 // Fig. 2.9: fig02_09.cpp 2 // Class average program with sentinel-controlled repetition. 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 using std::ios; 9 10 #include <iomanip> 11 12 using std::setprecision; 13 using std::setiosflags; 14 15 int main() 16 { 17 int total, // sum of grades 18 gradeCounter, // number of grades entered 19 grade; // one grade 20 double average; // number with decimal point for average 21 22 // initialization phase 23 total = 0; 24 gradeCounter = 0; 25 26 // processing phase 27 cout << "Enter grade, -1 to end: "; 28 cin >> grade; 29 30 while ( grade != -1 ) { Data type double used to represent decimal numbers.
  • 32. 31 total = total + grade; 32 gradeCounter = gradeCounter + 1; 33 cout << "Enter grade, -1 to end: "; 34 cin >> grade; 35 } 36 37 // termination phase 38 if ( gradeCounter != 0 ) { 39 average = static_cast< double >( total ) / gradeCounter; 40 cout << "Class average is " << setprecision( 2 ) 41 << setiosflags( ios::fixed | ios::showpoint ) 42 << average << endl; 43 } 44 else 45 cout << "No grades were entered" << endl; 46 47 return 0; // indicate program ended successfully 48 } Enter grade, -1 to end: 75 Enter grade, -1 to end: 94 Enter grade, -1 to end: 97 Enter grade, -1 to end: 88 Enter grade, -1 to end: 70 Enter grade, -1 to end: 64 Enter grade, -1 to end: 83 Enter grade, -1 to end: 89 Enter grade, -1 to end: -1 Class average is 82.50 setiosflags(ios::fixed | ios::showpoint) - stream manipulator ios::fixed - output numbers with a fixed number of decimal points. ios::showpoint - forces decimal point and trailing zeros, even if unnecessary: 66 printed as 66.00 | - separates multiple option. setprecision(2) - prints only two digits past decimal point. Programs that use this must include <iomanip> static_cast<double>() - treats total as a double temporarily. Required because dividing two integers truncates the remainder. gradeCounter is an int, but it gets promoted to double.
  • 33. Nested control structures • Problem: A college has a list of test results (1 = pass, 2 = fail) for 10 students. Write a program that analyzes the results. If more than 8 students pass, print "Raise Tuition". • We can see that – The program must process 10 test results. A counter- controlled loop will be used. – Two counters can be used—one to count the number of students who passed the exam and one to count the number of students who failed the exam. – Each test result is a number—either a 1 or a 2. If the number is not a 1, we assume that it is a 2.
  • 34. Nested control structures • High level description of the algorithm Initialize variables Input the ten quiz grades and count passes and failur Print a summary of the exam results and decide if tuition should be raised
  • 35. 1 // Fig. 2.11: fig02_11.cpp 2 // Analysis of examination results 3 #include <iostream> 4 5 using std::cout; 6 using std::cin; 7 using std::endl; 8 9 int main() 10 { 11 // initialize variables in declarations 12 int passes = 0, // number of passes 13 failures = 0, // number of failures 14 studentCounter = 1, // student counter 15 result; // one exam result 16 17 // process 10 students; counter-controlled loop 18 while ( studentCounter <= 10 ) { 19 cout << "Enter result (1=pass,2=fail): "; 20 cin >> result; 21 22 if ( result == 1 ) // if/else nested in while 23 passes = passes + 1;
  • 36. 3. Print results 24 else 25 failures = failures + 1; 26 27 studentCounter = studentCounter + 1; 28 } 29 30 // termination phase 31 cout << "Passed " << passes << endl; 32 cout << "Failed " << failures << endl; 33 34 if ( passes > 8 ) 35 cout << "Raise tuition " << endl; 36 37 return 0; // successful termination 38 } Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 2 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Enter result (1=pass,2=fail): 1 Passed 9 Failed 1 Raise tuition
  • 37. // Fig. 2.21: fig02_21.cpp // Calculating compound interest #include <iostream> using std::cout; using std::endl; using std::ios; #include <iomanip> using std::setw; using std::setiosflags; using std::setprecision; #include <cmath>
  • 38. int main() { double amount, // amount on deposit principal = 1000.0, // starting principal rate = .05; // interest rate cout << "Year" << setw( 21 ) << "Amount on deposit" << endl; // set the floating-point number format cout << setiosflags( ios::fixed | ios::showpoint ) << setprecision( 2 ); for ( int year = 1; year <= 10; year++ ) { amount = principal * pow( 1.0 + rate, year ); cout << setw( 4 ) << year << setw( 21 ) << amount << endl; } return 0; }