Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

Programming

Lecture 10
Dr. Badria Nabil
Control Structures (Repetition)
Part2
1
OBJECTIVES
• In this lecture you will learn:
• The essentials of counter-controlled repetition.
• To use the for and do…while repetition statements to execute
statements in a program repeatedly.
• To use the break and continue program control statements to
alter the flow of control.

2
Assignment 8
A college offers a course that prepares students for the state exam for
real estate brokers. Last year, ten of the students who completed this
course took the exam. The college wants to know how well its students
did on the exam. You have been asked to write a program to summarize
the results. You have been given a list of these 10 students. Next to each
name is written a 1 if the student passed the exam or a 2 if the student
failed.
Your program should analyze the results of the exam as follows:
1. Input each test result (i.e., a 1 or a 2). Display the prompting message
“Enter result” each time the program requests another test result.
2. Count the number of test results of each type.
3. Display a summary of the test results indicating the number of
students who passed and the number who failed.
4. If more than eight students passed the exam, print the message
“Raise
tuition.”

3
#include <iostream>
using namespace std;
int main()
{ int passes = 0;
Enter result ( 1=pass,2=fail ): 1
int failures = 0;
Enter result ( 1=pass,2=fail ): 2
int student = 1; Enter result ( 1=pass,2=fail ): 1
int result; Enter result ( 1=pass,2=fail ): 1
while ( student <=10 ) Enter result ( 1=pass,2=fail ): 1
{ cout<< "Enter result ( 1=pass,2=fail ): "; Enter result ( 1=pass,2=fail ): 1
Enter result ( 1=pass,2=fail ): 1
cin>> result ;
Enter result ( 1=pass,2=fail ): 1
if ( result == 1 ) { Enter result ( 1=pass,2=fail ): 1
passes ++; Enter result ( 1=pass,2=fail ): 1
} Passed 9
else { Failed 1
Raise tuition
failures ++;
}
student ++;
}
cout <<"Passed” << passes << “ \n” ;
cout <<"Failed“ << failures << “\n”;
if ( passes > 8 ) {
cout <<"Raise tuition\n" ;
}
return 0; } 4
#include <iostream> /* program with data validation*/
using namespace std;
int main()
{ int passes = 0;
int failures = 0;
int student = 1; Enter result ( 1=pass,2=fail ): 3
Wrong result
int result;
Enter result ( 1=pass,2=fail ): 5
while ( student <= 10 ) {
Wrong result
cout<< "Enter result ( 1=pass,2=fail ): "; Enter result ( 1=pass,2=fail ): 1
cin>> result ; Enter result ( 1=pass,2=fail ): 1
if ( result == 1 ) { Enter result ( 1=pass,2=fail ): 1
passes ++; Enter result ( 1=pass,2=fail ): 1
} Enter result ( 1=pass,2=fail ): 1
else if ( result == 2 ) { Enter result ( 1=pass,2=fail ): 1
failures ++; } Enter result ( 1=pass,2=fail ): 1
Enter result ( 1=pass,2=fail ): 1
else {
Enter result ( 1=pass,2=fail ): 1
cout <<“wrong result”;
Enter result ( 1=pass,2=fail ): 1
student -- ; Passed 10
} Failed 0
student ++; Raise tuition
} Press any key to continue
cout <<"Passed” << passes << “ \n” ;
cout <<"Failed“ << failures << “\n”;
if ( passes > 8 ) {
cout <<"Raise tuition\n“; }
return 0; }

5
Assignment Operators
• Assignment expression abbreviations
− Addition assignment operator
• Example
• c = c + 3; abbreviates to c += 3;
• Statements of the form
• variable = variable operator expression;
− can be rewritten as
• variable operator= expression;
• Other assignment operators
− d -= 4 (d = d - 4)
− e *= 5 (e = e * 5)
− f /= 3 (f = f / 3)
− g %= 9 (g = g % 9)
6
Assignment operator

• C=2 C +=7 C=? C=9



• D=5 D-=4 D=? D=1

• E=4 E*=5 E=? E=20

• F=6 F/=3 F=? F=2

• G=12 G%=9 G=? G=3

7
Increment and Decrement
Operators
• Increment operator ++
− Increments variable by one
• Example
• c++
• Decrement operator --
− Decrement variable by one
• Example
• c--

8
Increment and Decrement
Operators (Cont.)
• Preincrement
− When the operator is used before the variable
(++c or --c)
− Variable is changed, then the expression it is in is
evaluated using the new value
• Postincrement
− When the operator is used after the variable (c++
or c--)
− Expression the variable is in executes using the
old value, then the variable is changed

9
Increment and decrement
operators.
Sample
Operator Called Explanation
expression
++ preincrement ++a Increment a by 1, then use the new value of
a in the expression in which a resides.
++ postincrement a++ Use the current value of a in the expression
in which a resides, then increment a by 1.
-- predecrement --b Decrement b by 1, then use the new value of
b in the expression in which b resides.
-- postdecrement b-- Use the current value of b in the expression
in which b resides, then decrement b by 1.

10
1 // Fig. 4.21: fig04_21.cpp
2 // Preincrementing and postincrementing.
3 #include <iostream>
Outline
4 using std::cout;
5 using std::endl;
6
fig04_21.cpp
7 int main()
8 {
9 int c; (1 of 1)
10
11 // demonstrate postincrement
12 c = 5; // assign 5 to c
13 cout << c << endl; // print 5
14 cout << c++ << endl; // print 5 then postincrement
15 cout << c << endl; // print 6
16
17 cout << endl; // skip a line Postincrementing the c variable
18
19 // demonstrate preincrement
20 c = 5; // assign 5 to c
21 cout << c << endl; // print 5
22 cout << ++c << endl; // preincrement then print 6
23 cout << c << endl; // print 6
24 return 0; // indicate successful termination
25 } // end main Preincrementing the c variable
5
5
6

5
6
6
11
Increment and Decrement
Operators (Cont.)
• If c = 5, then
− cout << ++c;
• c is changed to 6
• Then prints out 6
− cout << c++;
• Prints out 5 (cout is executed before the
increment)
• c then becomes 6

12
Increment and Decrement
Operators (Cont.)
• When variable is not in an expression
− Preincrementing and postincrementing have
same effect
• Example
• ++c;
cout << c;
and
c++;
cout << c;
are the same

13
Practice

14
do…while Repetition Statement

• do…while statement
− Similar to while statement
− Tests loop-continuation after performing body
of loop
• Loop body always executes at least once

15
Using the do…while Loop
• do…while loops place the test at the end:

do
statement;
while ( termination );

int i = 1;
• Example: do {
cout << "i = " << i;
i++;
} while (i <= 10);
do…while Looping (Repetition)
Structure (continued)

17
1 // Fig. 5.7: fig05_07.cpp
2 // do...while repetition statement. Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6
Declare and initialize fig05_07.cpp
7 int main() control variable
8 { counter (1 of 1)
9 int counter = 1; // initialize counter
10
do…while loop displays counter’s
11 do
12 {
value before testing for counter’s
13 cout << counter << " "; // display counter final value
14 counter++; // increment counter
15 } while ( counter <= 10 ); // end do...while
16
17 cout << endl; // output a newline
18 return 0; // indicate successful termination
19 } // end main

1 2 3 4 5 6 7 8 9 10

18
do…while and While

19
Practice

20
for Repetition Statement
• for repetition statement
− Specifies counter-controlled repetition details in a single line of
code
• General form of the for statement
− for ( initialization; loopContinuationCondition; increment )
statement;
• Can usually be rewritten as:
− initialization;
while ( loopContinuationCondition )
• {
statement;
increment;
}
• If the control variable is declared in the initialization expression
− It will be unknown outside the for statement
21
Using the for Loop
• for loops are the most common loops:
for ( initialization; condition; iteration )
statement;

• Example:
for (i = 1; i <= 10; i++)
cout << i;

• How would this for loop look using a while


loop?
i=1;
While (i<=10)
{
Cout i;
i++;
}
1 // Fig. 5.2: fig05_02.cpp
2 // Counter-controlled repetition with the for statement.
Outline
3 #include <iostream>
4 using std::cout;
5 using std::endl;
6 fig05_02.cpp
7 int main()
8 { (1 of 1)
9 // for statement header includes initialization,
10 // loop-continuation condition and increment.
11 for ( int counter = 1; counter <= 10; counter++ )
12 cout << counter << " ";
13
14 cout << endl; // output a newline
Increment for counter
15 return 0; // indicate successful termination
16 } // end main Condition tests for counter’s final value
1 2 3 4 5 6 7 8 9 10 Control-variable name is counter with initial value 1

23
for statement header components.

24
Examples Using the for Statement

• for statement examples


− Vary control variable from 1 to 100 in increments of 1
• for ( int i = 1; i <= 100; i++ )
− Vary control variable from 100 to 1 in increments of -1
• for ( int i = 100; i >= 1; i-- )
− Vary control variable from 7 to 77 in steps of 7
• for ( int i = 7; i <= 77; i += 7 )
− Vary control variable from 20 to 2 in steps of -2
• for ( int i = 20; i >= 2; i -= 2 )
− Vary control variable over the sequence: 2, 5, 8, 11, 14, 17, 20
• for ( int i = 2; i <= 20; i += 3 )
− Vary control variable over the sequence: 99, 88, 77, 66, 55, 44, 33,
22, 11, 0
• for ( int i = 99; i >= 0; i -= 11 )

25
More on the for Loop

− Variables can be declared in the


initialization part of a for loop:
for (int i = 0; i < 10; i++)
cout << "i = " << i;

− Initialization and iteration can consist of a


list of comma-separated expressions:

for (int i = 0, j = 10; i < j; i++, j--) {


cout "i = " << i;
cout "j = " << j;
}
Guided Practice: Spot the Mistakes

int x = 10;
1
while (x > 0);
cout << x--;
Cout << "We have lift off!";

int x = 10;
while (x > 0)
2
cout << "x is " + x;
x--;

int sum = 0;
3
for (; i < 10; sum += i++);
Cout << "Sum is " + sum;
Mistakes
• Example 1
− The first example contains an extra semicolon at the end of the while. This is not a
compiler error; the compiler treats the semicolon as an empty loop body, as follows:

− while (x > 0)
− ; // Null loop body
• Example 2
− The problem with the second example is that x is not changed inside the loop. The x--
term is deemed to be outside the loop because there are no braces. Therefore, if x is
greater than zero the first time through the loop, it will always be greater than zero, and
the loop will never terminate.
• Example 3
− The problem with this example is that i is not initialized anywhere. The rest of the loop
is fine. Here is a description of what is happening:
• The loop keeps iterating while i is less than 10.
• The semicolon at the end of the for line indicates a null loop body.
• The iteration expression in the for loop adds i to sum, and then increments i
ready for the next loop iteration.

C++ Programming: From Problem Analysis to Program Design, Fourth Edition 28


Program to find the sum of the even
numbers from 0 to 10
#include <iostream>
using namespace std; Sum is 30
int main()
{
int sum = 0;
int N;
for ( N = 0; N <= 10; N += 2 ) {
sum += N;
}
cout<<"Sum is"<< sum <<"\n";
return 0;
}

29
Program to get power 2 of the
numbers from 1 to 10
#include <iostream>
Power 2 of 1 is 1
using namespace std; Power 2 of 2 is 4
int main() Power 2 of 3 is 9
{ Power 2 of 4 is 16
int p, i; Power 2 of 5 is 25
Power 2 of 6 is 36
for ( i = 1; i <= 10; i++) {
Power 2 of 7 is 49
p = i* i; Power 2 of 8 is 64
cout<<“The Pow2 of "<< i << " is\t "<< p << Power 2 of 9 is 81
"\n"; Power 2 of 10 is 100
}
return 0;
}

30
Assignment

1. Write a program to get the highest number


among 10 integer numbers
2. Write a program to output the multiplication
table of 6 from 1 to 10 6*1 = 6
6*2 = 12
6*3 = 18
6*4 = 24
6*5 = 30
6*6 = 36
6*7 = 42
6*8 = 48
6*9 = 54
6*10 = 60
31

You might also like