Unit 4 (C++) - Part Two
Unit 4 (C++) - Part Two
Unit 4 (C++) - Part Two
Part Two
FLOW OF CONTROL:-LOOPING (ITERATION)
Computer programs can be written to do a set of actions over and over. They do this
by using loops.
All loops must have a starting position, an ending position and something to do
over and over.
Types of Loops
There are two essentially different ways of knowing when a loop has been repeated
enough times.
1. When you know exactly how many loops you want to make.
An example of this would be if you wished this program to print the word Hello
exactly 7 times.
We will call a loop of this kind a COUNT-LOOP.
2. When some conditions has been fulfilled,
-This condition might be that a set of numbers should be written by the computer on the
screen, one after another until the number 99 is reached.. Then the looping should
stop.
-We will call this a Condition-Loop
• One method of controlling a loop is to create a special variable to keep track of the
number of times the loop has been executed. Such a variable called a counter.
• The counter is increased by a fixed amount (usually by 1) each time the loop is
executed.
LOOP CONTROL VARIABLE
• A loop control variable is a variable whose value is used to
determine the number of times a loop is repeated.
• The counter variable is an example of a loop control variable.
• This is mostly designated by either i, k, or m or n or words like
count.
• All loops contain some action that may be performed repeatedly, the
statements that perform such an action make up the loop body.
• Execution of the basic loop structure consists of the following five
steps:
1. The loop variable is initialized to a particular value before loop
execution begins.
2. The program tests the loop control variable to determine whether it
should execute the loop body or exit the loop.
3. The loop body, which can consist of any number of statements, is
executed.
4. At some point during execution, the value of the loop control variable
must be modified to allow exit from the loop.
5. The loop is existed when the test in Step 2 determines that the right
number of loop repetitions has been made. Execution continues with
the next statement following the loop.
1. FOR LOOP
Syntax
for(expression1;expression2;expression3)
{
//Action statement (Body of the Loop)
}
The for statement is a loop instruction that provides
i) An initialization part.
ii) An expression- evaluation for terminating the loop and
iii) A part to separate for the next iteration of the loop.
All three expression are required, but a null statement is valid for
one of the expression.
The semicolon separating the expressions are required.
The expression in the for statement are:
1. Expression1
It is initialization part
It is always executes just once, as the first step in the execution
process.
2. Expression2
is the test-expression condition for terminating the loop.
The test expression condition is evaluated each time to
see if the body should execute.
The body executes when the result of the expression is
True.
3. Expression3
is the part which prepares for the next iteration of the
loop.
is also executes one for each time the body of the
instruction executes.
This expression usually manipulates a variable that is
used in expression2.
The above syntax can be rewritten as:
for (variable initialization,
conditional expression, modification of variable)
• The variable initialization allows you to either declare a
variable and give it a value or give a value to an already
declared variable.
• Second, the conditional expression tells the program
that while the conditional expression is True, the loop
should continue to repeat it self.
• The variable modification section is the easiest way for
a loop to handle changing of the variable.
• It is possible to do things like
x++
x=x+10 or
• Even x=random(5)
The following example shows count down using a for
loop
//count down using a for loop
#include<iostream.h>
int main ()
{
for(int n=10;n>0;n--)
{
cout<<n<<“,”;
}
cout<<“FIRE!”;
return 0;
}
What is the output of this program?
• The initialization and increase fields are optional.
They can be avoided but not the semi colon signs among
them. For example, we would write:
for(;n<10;) if we want to specify no initialization and no
increase; or
for(;n<10;n++) if we want to include an increase field but
not initialization.
Optionally, using the comma operator (,) we can specify
more than one instruction in any of the fields included in
a for loop, like in initialization.
Example, Suppose that we want to initialize more than one
variable in our loop
for(n=0,i=100;n!=i; n++ ,i--)
{
//what ever here
}
This loop will execute 50 times if neither n nor i are
modified with in the loop.
• n starts with 0 and i with 100 , the condition is
(n!=i) (that n be not equal to i), because n is
increased by one and i decreased by one.
• The loop’s condition will become false after the
50th loop, when both n and i will be equal to 50.
The Flow chart of FOR Structure
• The following for loop prints the first 10 non negative integers:
for (i = 0; i < 10; i++)
cout << i << " ";
cout << endl;
• The initial statement, i = 0;, initializes the int variable i to 0.
• Next, the loop condition, i < 10, is evaluated. Because 0 < 10 is
true, the print statement executes and outputs 0.
• The update statement, i++, then executes, which sets the value
of i to 1.
• Once again, the loop condition is evaluated, which is still true,
and so on.
• When i becomes 10,the loop condition evaluates to false, the
for loop terminates, and the statement following the for loop
executes.
Example 1
#include<iostream.h>
int main ()
{
//The loop goes while x<100, and x
//increased //by one every loop
for(int x=0;x<100;x++)
{
cout<<x<<endl; //output in x
}
return 0;
}
• In the above program, x is set to zero, while x is less than 100
it calls cout<<x<<endl; and it adds 1 to x until the loop ends.
• Keep in mind also that the variable is incremented after the
code in the loop is run for the first time.
A for loop can have either a simple or compound statement.
The following examples further illustrate how a for loop
executes.
1. The following for loop outputs C++ Programming! and a
star (on separate lines) five times:
for (int i = 1; i <= 5; i++)
{
cout << " C++ Programming “<< endl;
cout << "* " << endl;
}
2. Consider the following for loop:
for (int i = 1; i <= 5; i++) {
cout << “C++ Programming!" << endl;
}
cout << "* " << endl;
• This loop outputs C++ Programming! five times and the star
only once.
• Note that the for loop controls only the first output statement
because the two output statements are not made into a
compound statement.
• Therefore, the first output statement executes five times
because the for loop body executes five times.
• After the for loop executes, the second output statement
executes only once.
• The indentation, which is ignored by the compiler, is
nevertheless misleading.
// The ff Program to determine sum and average of the first n positive
numbers.
#include <iostream.h>
main() {
int counter; sum, n, average;
cout << " Enter the number of positive integers";
cin >> n;
sum = 0;
cout << endl;
for (counter = 1; counter <= n; counter++)
sum = sum + counter;
average=sum/n;
cout<< “Sum= "<<sum<< endl;
cout<<“Avaerage= "<<average<< endl;
}
Example 1
1. Write a program using for loop to print “Welcome to
C++ Programming Course” statement ten(10) times.
#include<iostream.h>
#include<conio.h>
int main ()
{
int i;
for(i=0;i<10;i++)
{
cout<<“Welcome to C++ Programming Course”<<endl;
}
getch();
return 0;
}
Example 2
2. Write C++ program to print consecutive integers ( 1
through 10) using for loop.
#include<iostream.h> Output
#include<conio.h> 1
int main () 2
{ 3
4
clrscr ();
5
int digit;
6
for(digit=1;digit<=10;++digit)
7
{
8
cout<<digit<<“\n”; 9
} 10
getch();
return 0;
}
3. Write C++ program to print consecutive integers (1 to 5)
with one digit on each line. Use a for statement in which by
omitting expression 1 and expression 3
#include<iostream.h>
#include<conio.h> Output
int main ()
//display the number 1 through 5 1
{ 2
int digit=1;
for(;digit<=5;) 3
{ 4
cout<<“\n”<<digit++;
} 5
getch ();
return 0;
}
Nested for Loop
• Loops may be nested, with one loop sitting in the body
of another.
• The inner loop will be executed in full for every
execution for the outer loop.
• In for loop for example, if there is one for statement,
there will be another for statement to be nested.
• Usually used in matrix calculations.
Ex. Row
Column
Two Loop
//This program prints a multiplication table to implement //the
nested for--loop:
#include <iomanip.h> // defines setw()
#include <iostream.h> // defines cout
int main(){
for (int x=1; x <= 12; x++){
for (int y=1; y <= 12; y++){
cout << setw(4) << x*y;
}
cout << endl;
}
}
The output of this program is the following, that displays the
multiplication table.
• Each iteration of the outer x loop prints one row of the
multiplication table.
• For example, on the first iteration when x = 1, the inner y loop
iterates 12 times, printing 1*y for each value of y from 1 to 12.
• And then on the second iteration of the outer x loop when x =
2, the inner y loop iterates 12 times again, this time printing
2*y for each value of y from 1 to 12.
• Note that the separate cout << endl; statement must be
inside the outer loop and outside the inner loop in order to
produce exactly one line for each iteration of the outer
loop.
• This program uses the stream manipulator setw to set the
width of the output field for each integer printed.
• The expression setw(4) means to “set the output field
width to 4 columns” for the next output.
• This aligns the outputs into a readable table of 12 columns
of right-justified integers.
• Stream manipulators are defined in the <iomanip.h>
header, so this program had to include the directive
#include <iomanip.h> in addition to including the
<iostream.h> header.
Exercise
a) * * * * b) * c) * * * *
**** *****
**** *** **
*****
d) * e) *
*** **
***** ***
******* ****
f) # * * * *
* # ** *
* * #* *
* * * # *
* * * * #
THE break STATEMENT
• We can also use break statement in loops as that of switch statement.
• When it executes, it terminates the loop, “breaking out” of the iteration at that
point.
• The following program reads a sequence of positive integers, terminated by 0, and
prints their average:
#include<iostream.h>
int main() {
int n, count=0,sum=0;
cout << "Enter positive integers (0 to quit):" << endl;
for (;;) //forever
{
cout << "\t" << count+1<<":";
cin >> n;
if (n <= 0) break;
++count;
sum += n;
}
cout << “Average of those " << count << " positive numbers is "
<< float(sum)/count << endl;
}
• When 0 is input, the break executes, immediately terminating the
for loop and transferring execution to the final output statement.
• Without the break statement, the ++count statement would have
to be put in a conditional, or count would have to be decremented
outside the loop or initialized to –1.
• Note that all three parts of the for loop’s control mechanism are
empty: for (;;).
• This construct is pronounced “forever.” Without the break, this
would be an infinite loop.
• When used within nested loops, the break statement applies only to the
loop to which it directly belongs; outer loops will continue, unaffected
by the break.
Using a break Statement with Nested Loops
• Since multiplication is commutative (e.g.,3×4=4×3), multiplication
tables are often presented with the numbers above the main diagonal
omitted.
• This program prints a triangular multiplication table:
#include<iostream.h>
#include<iomanip.h>
int main(){
for (int x=1; x <= 12; x++){
for (int y=1; y <= 12; y++)
if (y > x) break;
else cout << setw(4) << x*y;
cout << endl;
}
}
• When y>x, the execution of the inner y loop terminates and the next
iteration of the outer x loop begins.
• For example, when x =3,they loop iterates 3 times (with y = 1, 2, 3),
printing 3 6 9.
• Then on its 4th iteration, the condition (y > x) is true, so the break
statement executes, transferring control immediately to the cout << endl
statement (which is outside of the inner y loop).
• Then the outer x loop begins its 4th iteration with x =4
THE continue STATEMENT
• The break statement skips the rest of the statements in the loop’s
block, jumping immediately to the next statement outside of the
loop. The continue statement is similar.
• It also skips the rest of the statements in the loop’s block, but
instead of terminating the loop, it transfers execution to the next
iteration of the loop.
• It continues the loop after skipping the remaining statements in its
current iteration.
Using continue and break Statements
• This little program illustrates the continue and break statements:
#include<iostream.h>
main(){
int n;
for (;;){
cout << "Enter int: ";
cin >> n;
if (n%2 == 0) continue;
if (n%3 == 0) break;
cout << "\tBottom of loop.\n";
}
cout << "\tOutside of loop.\n";
}
• When n has the value 7, both if conditions are false and control reaches
the bottom of the loop.
• When n has the value 4, the first if condition is true (4 is a multiple of 2),
so control skips over the rest of the statements in the loop and jumps
immediately to the top of the loop again to continue with its next iteration.
• When n has the value 9, the first if condition is false (9 is not a multiple
of 2) but the second if condition is true (9 is a multiple of 3), so control
breaks out of the loop and jumps immediately to the first statement that
follows the loop.
THE goto STATEMENT
• The break statement, the continue statement, and the
switch statement each cause the program control to
branch to a location other than where it normally would
go.
The destination of the branch is determined by the context:
break goes to the next statement outside the loop,
continue goes to the loop’s continue condition, and
switch goes to the correct case constant.
• All three of these statements are called jump statements
because they cause the control of the program to “jump
over” other statements.
• The goto statement is another kind of jump statement.
• Its destination is specified by a label within the statement.
• A label is simply an identifier followed by a colon placed
in front of a statement.
• Labels work like the case statements inside a
switch statement: they specify the destination of
the jump.
• The following example illustrates, how a break
normally behaves within nested loops: execution
breaks out of only the innermost loop that contains
the break statement.
• Breaking out of several or all of the loops in a nest
requires a goto statement, as the next example
illustrates.
Using a goto Statement to Break Out of a Nest of Loops
#include<iostream.h>
int main() {
const int n=5;
for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
for (int k=0; k<n; k++)
if (i+j+k>n) goto esc;
else cout << i+j+k << " ";
cout << "* ";
}
esc: cout << "." << endl; // inside the i loop,outside the j loop
}
}
Top and Bottom Tested Loop
• Control structures are commands that choose which
lines of code will be executed.
• Some control structures you have already seen are the if
command and the for command.
• A for loop like the following is a good way to repeat
commands if you know how many times they must be
repeated.
for(count=0;count<10;count++)
{
//code here is done 10 times
}
However, this is not convenient if you do not know how
many times the loop will have to be executed.
• There are two ways to set up a loop that determines
when to quit after it has started being repeated.
• These are called a top tested loop and a bottom
tested loop.
Definition
1. A top tested loop is one in which the conditions for running the
loop are tested before the loop is executed.
As such, the loop may not be executed even once.
• A top tested loop in C++ looks like this.
while (menu_pick !=0)
{
//do these commands until menu_pick equals 0
}
2. A bottom tested loop is one that decides whether to do the loop
again after it has been executed.
Because of this, the loop is always executed the first time and will
repeat until the condition is met.
A bottom tested loop in C++ looks like this.
do
{
//run these commands, then decide whether to do them again
}
while (menu_pick !=0);
1. While Structure (Top Tested Looping)
}
}
cout<<“You entered “<<count
<<“Integers and the integers are in ascending order.\n”;
}
• The following is the sample output of above program
Please enter five integers, separated by a carriage return.
12
34
56
78
90
You entered 5 integers and the integers are in ascending order.
Return the program and see interactively:
Please enter five integers, separated by carriage return
12
24
36
23
The number_in position 4 is out of order.
TERMINATING A LOOP
#include<iostream.h>
#include<conio.h>
int main() {
long bound;
cout << "Enter a positive integer: ";
cin >> bound;
cout << "Fibonacci numbers<"<< bound << ":\n0,1";
long f0=0,f1=1;
while (true)
{ long f2 = f0 + f1;
if (f2 > bound) exit(0); // terminates the program immediately
cout << "," << f2;
f0 = f1;
f1 = f2;
}
}
2. Do-while Statement
• The do-while statement is a loop statement that allows its body of
instructions to be executed one or more times.
• The syntax for the do..while statement is
do {
statement
}
while (condition);
• where condition is an integral expression and statement is any executable
statement.
• It repeatedly executes the statement and then evaluates the condition until
that condition evaluates to false.
• The do..while statement works the same as the while statement except that
its condition is evaluated at the end of the loop instead of at the beginning.
• This means that any control variables can be defined within the loop
instead of before it.
• It also means that a do...while loop will always iterate at least once,
regardless of the value of its control condition.
Example 1: Using do----while loop to print
the following output: 0 5 10 15 20
#include<iostream.h>
int main (){
int i = 0;
do
{
cout << i << " ";
i = i + 5;
}
while (i <= 20);
return 0;
}
Example 2:Using a do..while Loop to Compute a Sum
of Consecutive Integers
#include<iostream.h>
int main()
{
int n,i=0;
cout << "Enter a positive integer: ";
cin >> n;
long sum=0;
do {
sum += i++;
}
while (i <= n);
cout << "The sum of the first " << n << " integers is " << sum;
}
Example 3
• This program prints all the factorial numbers up to an input
limit:
#include<iostream.h>
int main() {
long bound;
cout << "Enter a positive integer: ";
cin >> bound;
cout << "Factorial numbers "<< bound << ":\n1,1";
long f=1,i=1;
do {
f *= ++i;
cout << "," << f;
}
while (f < bound);
}