C++ Programming Structures (Part III) QF002/4/1
UNIT4
General Objective : To understand and identify the fundamental concept of repetition structure.
Specific Objective : At the end of the unit you should be able to:-
Recognize the repetition structure.
Differentiate the repetition structure.
Write and design a simple program using the
repetition structure.
________________________________________________________________________
OBJECTIVES
C++ PROGRAMMING STRUCTURES (Part III)
C++ Programming Structures (Part III) QF002/4/2
4.0 Repetition Structure
The repetition structure allow a sequence of instructions to
be executed repeatedly until a certain condition is reached.
This structure comes in three forms:
4.1 While Statement
A while structure allows the program to repeat a set of
statements as long as the starting condition remains true.
‘True’ is used in the Boolean sense and so the condition for
the loop to continue must evaluate to true or false.
The program evaluates the condition if it is true then the
statements inside the braces are executed. The condition is
evaluated again. This will continue until the condition is
false and the program jumps to the next line after the body of
the structure. If only one statement is used in the while loop
then the braces are not required.
________________________________________________________________________
INPUT
a.
b.
c. For
C++ Programming Structures (Part III) QF002/4/3
The while statement construct has the general form
The expression is first evaluated,
If it is TRUE the statement block is executed
If it is FALSE, the statement block is skipped
Figure 4.2: Flowchart Of While Statement Structure
________________________________________________________________________
While (expression) statement block;
Figure 4.1: A While Statement Structure
exp Statement
No
Yes
A while structure allows the program to repeat as long as the condition remains true
Ahha.. Error?
C++ Programming Structures (Part III) QF002/4/4
Here is an example of the programming using while statement
2: // while statements3:4: #include <iostream.h>5:6: int main()7: {8: unsigned short small;9: unsigned long large;10: const unsigned short MAXSMALL=65535;11:12: cout << "Enter a small number: ";13: cin >> small;14: cout << "Enter a large number: ";15: cin >> large;16:17: cout << "small: " << small << "...";18:19: // for each iteration, test three conditions20: while (small < large && large > 0 && small < MAXSMALL)21:22: {23: if (small % 5000 == 0) // write a dot every 5k lines24: cout << ".";25:26: small++;27:28: large-=2;29: }30:31: cout <<"\nSmall:"<< small << " Large:" << large <<endl;32: return 0;33: }
Figure 4.3: An Example Of While Statement Structure
________________________________________________________________________
C++ Programming Structures (Part III) QF002/4/5
Analysis: This program is a game. Enter two numbers, one
small and one large. The smaller number will count up by
ones and the larger number will count down by twos. The
goal of the game is to guess when they will meet.
In lines 12-15, the numbers are entered. Line 20 sets up a
while loop which will continue only as long as three
conditions are met small is not bigger than large; large isn't
negative and small doesn't overrun the size of a small integer
(MAXSMALL).
In line 23, the value in small is calculated modulo 5,000.
This does not change the value in small; however, it only
returns the value 0 when small is an exact multiple of 5,000.
Each time a dot (.) is printed to the screen to show progress.
In line 26, small is incremented and on line 28, large is
decremented by 2.
When any of the three conditions in the while loop fails, the
loop ends and execution of the program continues after the
while loop's closing brace in line 29.
An Output of the program
Output: Enter a small number: 2Enter a large number: 100000small: 2.........Small: 33335 Large: 33334
Figure 4.4 :An Output Of While Statement Structure
________________________________________________________________________
C++ Programming Structures (Part III) QF002/4/6
4.2 Do- while statement
A variation on the simple while loop is the do while
structure. The do part contains the body and is executed as
long as the while condition remains true.
The difference between these two while structures are that
with a simple while loop the condition is evaluated first
and if it is immediately false, the body is never executed. In
the do while loop, the body is executed before the condition
is tested and so guaranteed to be executed at least once.
Figure 4.5 below shows the general form of do-while
structure
Figure 4.5: A Do- While Statement Structure
Figure 4.6: A Do- While Statement Structure
________________________________________________________________________
Do Statement block
While (expression);
exp
Statement
No
Yes
C++ Programming Structures (Part III) QF002/4/7
A simple program
// Program to illustrate a do while loop
#include <ios.stream.h>
void main()
{
int selection;
do
{
cout << “\n Menu\n”;
cout << “\n 0. Exit\n”;
cout << “\n 1. Append\n”;
cout << “\n 2. Delete\n”;
cout << “\n 3. Modify\n”;
cout << “\n\n Enter Selection: ”;
cin >> selection;
} while(selection >0 && selection < 4);
// The do loop is repeated if the expression is
true
}
Figure 4.7 : A Do- While Statement Structure
________________________________________________________________________
The main difference is that in the while statement, the conditional expression is evaluated at the top of the loop, while in the do-while statement, the conditional expression is evaluated at the bottom of the loop. Therefore, the statements controlled by the do-while statement are executed at least once.
What is the difference between the while and do-while statements?
C++ Programming Structures (Part III) QF002/4/8
An Output of a simple Program
Figure 4.8 An Output Of Do-While Statement Structure
________________________________________________________________________
In the Do- while loop, the body is executed before the condition is tested and executed at lest one
In the While loop the condition is evaluated first and if it is immediately false, the body is never executed
C++ Programming Structures (Part III) QF002/4/9
Test your comprehension before continuing the next input.Check your answers on the next page.
4.1 What is repetition structure?
4.2 Name the components of the repetition structure.
4.3What is the main difference between the while and do-while
statements?
4.4 Can the while statement end with a semicolon?
4.5Develop a simple program to print cubes by using while
statement
________________________________________________________________________
Activity 4a
C++ Programming Structures (Part III) QF002/4/10
Make sure you have tried to answer all the questions given.you can
check your answers with the answers below.
4.1. The repetition structure permits a sequence of the instructions to
be executed repeatedly until a certain condition is reached.
4.2. The components of repetition structure are:
a. While
b. Do- while
c. For
4.3. The main difference is that in the while statement, the
conditional expression is evaluated at the top of the loop,
while in the do-while statement, the conditional expression is
evaluated at the bottom of the loop. Therefore the statements
controlled by the do-while statements are executed at least
once.
4.4. By definition, the while statement does not end with a
semicolon. However, it is legal in C to put a semicolon right
after the while statement
________________________________________________________________________
Feedback 4a
C++ Programming Structures (Part III) QF002/4/11
4.5. Example of the While structure program :-
#include<iostream.h>
main()
{
int n;
cout<< “Enter positif integers. Terminate with
0.\n\t: “;
cin>>n;
while (n>0) {
cout << n<< “cubed is “ <<n*n*n<<”\n\t:
“;
cin >> n;
}
}
________________________________________________________________________
C++ Programming Structures (Part III) QF002/4/12
4.3 For statement
The for structure has the general form as the while structure.
Figure 4.9 A For Statement Structure
The initialization part is used to initialize any variable(s) that
may need to be initialized. This part is performed just once at
the start of the loop.
The expression part determines whether the loop execution
should continue. If the value of the expression is TRUE (non
zero), the statements block will be executed otherwise the loop
will be terminated.
The incremented part typically increments or decrements the
loop index. This performed every time through the loop
iteration. This part is used to increment any variable(s) that
may need to be incremented.
________________________________________________________________________
for(initialization ;expression; incrementation) statement block;
For loop expression is not
terminated with semicolon
Remember that!!!!!
Yes….Sir!!!
C++ Programming Structures (Part III) QF002/4/13
A simple program
#include <iostream.h>
void main()
{
int i, sum, sum2;
for (i=2,sum=0,sum2=0;i<=20; i = i+2)
{
sum = sum + i;
sum2= sum2 + i * i;
}
cout << “\n Sum of first 20 even natural numbers = “
<< sum;
cout << “\n Sum of their squares = << sum2;
}
Figure 4.10 An Example Of A Simple Program
Figure 4.11 An Output Of A Simple Program
________________________________________________________________________
C++ Programming Structures (Part III) QF002/4/14
4.4 Break And Continue Statement
Two commands that can be included in looping processes are
continue and break. The continue statement, when included in
the body of the loop causes the program to return immediately
to the start of the loop and ignore any remaining part of the
body. The break statement causes the program to immediately
exit from the loop and resume at the next line of the program
4.5 The break statement
The special statement "break" causes the loop to be abandoned
and execution continues following the closing curly brace.
Figure 4.12 A Statement Of Break Statement
The figure above shows the program continues after the end of
the loop. Within a nested loop, "break" causes the innermost
loop to be abandoned.
________________________________________________________________________
while ( i > 0 ) { ....; if ( j == .... ) { break; // abandon the loop } ....; } // end of the loop body
cout << "continues here ...\n";
C++ Programming Structures (Part III) QF002/4/15
4.6 The continue statement
The continue statement is to terminate loop but also goes back to the beginning of the loop’s block to begin the next iteration.
An example of a simple program
#include <iostream.h>
main()
{
int n;
for (;;){
cout << “Enter int: “; cin >> n;
if (n%2 = = 0) continue;
else if (n%3 = = 0) break;
cout << “\t Bottom of loop.\n”;
}
cout << “\t Outside of loop.\n”;
}
Figure 4.12 An Example Of A Simple Program
________________________________________________________________________
Kamal… what can the continue statement do inside a loop ?
Sh…. When the continue statement inside a loop is executed, the program control is branched back to the beginning of the loop so that another iteration can be started.Emmm…..
C++ Programming Structures (Part III) QF002/4/16
An output of a simple program
Figure 4.13 An Output Of A Simple Program
________________________________________________________________________
The go to statement enables the computer to jump to same other spot in your computer.
C++ Programming Structures (Part III) QF002/4/17
Test your comprehension before continuing the next inputCheck your answers on the next page.
4.6. What is break statement used for?
4.7. What is continue statement used for?
4.8. Write a simple program using for statement to calculate the square root of even number.
4.9. What can the continue statement do inside a loop?
________________________________________________________________________
Activity 4b
C++ Programming Structures (Part III) QF002/4/18
Make sure you have tried to answer all the questions given. You can check your answers with the answers below
4.6. The break statement is used to terminate the switch
construct or a loop.
4.7. The continue statement is used to let you stay within a loop
while skipping over some statements.
4.8.
main()
{
float x;
cout << “Enter a positive number: ”;
cin >> x;
for (int n = 1; n * n <= x, n++)
;
cout <<“The integer square root of“ << x >>“is”
<< n – 1 << endl;
}
________________________________________________________________________
Feedback 4b
C++ Programming Structures (Part III) QF002/4/19
4.9.When the continue statement inside a loop is executed, the
program control is branched back to the beginning of the loop
so that another iteration can be started. Inside the loop, any
statements following the continue statement will be skipped
over each other if the continue statement is executed.
________________________________________________________________________
C++ Programming Structures (Part III) QF002/4/20
The while structure allows the program to repeat a set of statements as long as the starting condition remains true.
In the do-while statemant, the conditional expression is evaluated at the bottom of the loop.
The Do- while loop, the body is executed before the condition is tested and executed at lest one.
The break statement causes the loop to be abandoned and execution continues following the closing curly brace.
The continue statement is to terminate loop but also goes back to the beginning of the loop’s block to begin the next iteration.
________________________________________________________________________
Key Facts
C++ Programming Structures (Part III) QF002/4/21
You are approaching success, please answer the questions below. If you
have any problems, please discuss it with your lecturer. Wish you good
luck and all the best.
Question 4-1
a. Is it possible to nest while loops within for loops?
b. Is it possible to create a loop that never ends? Give an example.
c Write a while loop to count from 100 to 200 by 2s.
d. Write a do...while loop to count from 100 to 200 by 2s.
e. What is wrong with this code?
int counter = 0
while (counter < 10)
{
cout << "counter: " << counter;
counter++;
}
________________________________________________________________________
Self-Assessment
C++ Programming Structures (Part III) QF002/4/22
f. What is wrong with this code?
int counter = 100;
while (counter < 10){
cout << "counter now: " << counter;
counter--;}
Question 4-2.
a. How do I initialize more than one variable in a for loop?
b. Why is goto should be avoided?
c. Is it possible to write a for loop with a body that is never
executed?
d. What is the value of x when the for loop completes?
for (int x = 0; x < 100; x++)
e. Write a nested for loop that prints a 10x10 pattern of 0s.
f. Write a for statement to count from 100 to 200 by 2s.
for (int x = 100; x<=200; x+=2)
________________________________________________________________________
C++ Programming Structures (Part III) QF002/4/23
g. What wrong with this code?
for (int counter = 0; counter < 10; counter++);
cout << counter << "\n";
h. What wrong with this code?
cout << "Enter a number between 0 and 5: ";
cin >> theNumber;
switch (theNumber)
{
case 0:
doZero();
case 1: // fall through
case 2: // fall through
case 3: // fall through
case 4: // fall through
case 5:
doOneToFive();
break;
default:
doDefault();
break;
}
________________________________________________________________________
C++ Programming Structures (Part III) QF002/4/24
Make sure you have tried to answer all the questions given. You can
check your answers with the answers below.
Answer 4-1
a. Yes. Any loop can be nested within any other loops.
b. Yes. Following are examples for both a for loop and a while
loop:
for(;;)
{
// This for loop never ends!
}
while(1)
{
// This while loop never ends!
}
c
int x = 100;
while (x <= 200)
x+= 2;
________________________________________________________________________
Feedback On Self-assessment
C++ Programming Structures (Part III) QF002/4/25
d.
int x = 100;
do
{
x+=2;
} while (x <= 200);
e.
int counter = 0
while (counter < 10)
{
cout << "counter: " << counter;
counter++;
}
The counter is never incremented and the while
loop will never terminate.
f.
int counter = 100;
while (counter < 10){
cout << "counter now: " << counter;
counter--;}
The counter is initialized to 100, but the test condition is that if it is
less than 10, the test will fail and the body will never be executed. If
line 1 were changed to int counter = 5;, the loop would not terminate
until it had counted down past the smallest possible int. Because int
is signed by default, this would not be what has been intended.
________________________________________________________________________
C++ Programming Structures (Part III) QF002/4/26
Answer 4-2.
a. Separate the initializations with commas, such as
for (x = 0, y = 10; x < 100; x++, y++)
b. goto jumps in any direction to any arbitrary line of code. This
makes for source code that is difficult to understand and therefore
difficult to maintain.
c. Yes, if the condition is FALSE after the initialization, the body of
the for loop will never execute. Here's an example:
for (int x = 100; x < 100; x++)
d. 100
e.
for (int i = 0; i< 10; i++)
{
for ( int j = 0; j< 10; j++)
cout << "0";
cout << "\n";
}
f.
for (int x = 100; x<=200; x+=2)
________________________________________________________________________
C++ Programming Structures (Part III) QF002/4/27
g.
for (int counter = 0; counter < 10;
counter++); cout << counter << "\n";
There is a semicolon after the loop, and the loop does nothing.
The programmer may have intended this, but if counter was
supposed to print each value, it won't.
h. Case 0 probably needs a break statement. If it does not, it should be
documented with a comment
________________________________________________________________________
CONGRATULATIONSMay success be with you always……..
Top Related