0% found this document useful (0 votes)
4 views

CSC201 - Week9

The document provides an overview of iteration in C++, detailing the three types of loops: while, do...while, and for statements. It explains their syntax, usage, and key characteristics, including examples of each loop type in action. Additionally, it highlights the importance of controlling loop execution and avoiding infinite loops.

Uploaded by

Yasir Idris
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

CSC201 - Week9

The document provides an overview of iteration in C++, detailing the three types of loops: while, do...while, and for statements. It explains their syntax, usage, and key characteristics, including examples of each loop type in action. Additionally, it highlights the importance of controlling loop execution and avoiding infinite loops.

Uploaded by

Yasir Idris
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 39

Week 9 – ITERATION

Course Lecturer:
Haruna Musa
([email protected])

Department of Computer Science, FUD -


2015/2016
 Iterationis the repetition of a statement or
block of statements in a program.

 C++ has three iteration statements:


 the while statement
 the do…while statement
 the for statement.

 Iteration
statements are also called loops
because of their cyclic nature.
 The while statement is one of several C++
construct statements.

 Each construct (from construction) is a


programming language statement— or a
series of statements—that controls looping.

 The while, like other such statements, is a
looping statement that controls the execution
of a series of other statements.
The format of the while statement is

while (test expression)


{
block of one or more C++ statements;
}
 The parentheses around test expression are
required.

 As long as test expression is True (nonzero), the


block of one or more C++ statements executes
repeatedly until test expression becomes False
(evaluates to zero).
 Bracesare required before and after the body
of the while loop, unless you want to execute
only one statement.

 Each statement in the body of the while loop


requires an ending semicolon.

 The placeholder test expression usually


contains relational, and possibly logical,
operators.
 These operators provide the True - False
condition checked in test expression.

 Iftest expression is False when the program


reaches the while loop for the first time, the
body of the while loop does not execute at all.
 You use the loop concept in everyday life.

 Any time you have to repeat the same procedure,


you are performing a loop—just as your computer
does with the while statement.

 Suppose you are wrapping holiday gifts.

 The following statements represent the looping


steps (in while format) that you follow while gift-
wrapping.
while (there are still unwrapped gifts)
{
Get the next gift;
Cut the wrapping paper;
Wrap the gift;
Put a bow on the gift;
Fill out a name card for the gift;
Put the wrapped gift with the others;
}
 Whether you have 3, 15, or 100 gifts to
wrap, you use this procedure (loop)
repeatedly until every gift is wrapped.

 The following program is short, but it


demonstrates a while loop that ensures valid
keyboard input.
#include <iostream.h>
main()
{
char ans;
cout << “Do you want to continue (Y/N)? “;
cin >> ans; // Get user’s answer
while ((ans != ‘Y’) && (ans != ‘N’))
{ cout << “\nYou must type a Y or an N\n”; // Warn
// and ask
cout << “Do you want to continue (Y/N)?”; // again.
cin >> ans;
} // Body of while loop ends here.
}
 If
users type something other than Y or N, the
program prints an error message, asks for
another answer, and then checks the new
answer.

 The while loop tests the test expression at the


top of the loop.

 This is why the loop might never execute.

 If
the test is initially False, the loop does not
execute even once.
The following program is an example of an invalid
while loop. See if you can find the problem.

#include <iostream.h>
int main()
{
int a=10, b=20;
while (a > 5)
{ cout << “a is “ << a << “, and b is “ << b << “\n”;
b = 20 + a; }
return 0;
}
 This while loop is an example of an infinite
loop

 It
is vital that at least one statement inside the
while changes a variable in the test
expression (eg. a) otherwise, the condition is
always True.

 Because the variable a does not change inside


the while loop, this program will never end.
Example: this program computes the sum 1+2+3+…
+n for an input integer n;
#include<iostream>
Int main()
{ int n, i=1;
Cout<< “enter a positive integer:”;
Cin>>n;
Long sum =0;
While (i<=n)
Sum+=i++;
Cout<< “the sum of the first”<<n<< “integers
is”<<sum<<endl;
}
 Thisprogram uses three local variables: n, i, and
sum. Each time the while loop iterates, is
incremented and then added to sum. The loop stops
when i=n, so n is the last value to sum.
 We have seen how the break statement is
used to control the switch statement.

 Thebreak statement is also used to control


loops

 Example: this program shows the effect of


break statement.
 #include<iostream>
 Int main()
 { int n, i=1;
 Cout<< “enter a positive integer:”;
 Cin>>n;
 Long sum = 0;
 While (true)
 { if (i>n) break; //terminating the loop

immediately;
 Sum+=i++;
 }
 Cout<< “the sum of the first”<<n<< “integers

is”<<sum<<endl;
 }
 This runs as soon as the value I reaches n

 theloop terminates and the output statement at the


end of the program executes

 Note that the control condition on the while loop


itself is true, which means continue forever

 Oneadvantage of using a break statement inside a


loop is that it causes the loop to terminate
immediately, without having to finish executing the
remaining statements in the loop block.
 The do…while statement controls the do…
while loop, which is similar to the while loop
except the relational test occurs at the end
(rather than beginning) of the loop.

 This ensures the body of the loop executes at


least once.

 The do-while tests for a positive relational


test; as long as the test is True, the body of
the loop continues to execute
The syntax for the do…while statement is :
do
{
block of one or more C++ statements;
}
while (condition)

Condition must be enclosed in parentheses,


just as it must in a while statement.

 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 values of its
control condition.
#include <iostream.h>
int main()
{
char ans;
do
{ cout << “\nYou must type a Y or an N\n”; // Warn
// and ask
cout << “Do you want to continue (Y/N) ?”; // again.
cin >> ans; } // Body of while loop
// ends here.
while ((ans != ‘Y’) && (ans != ‘N’));
return 0;
 Example2: Suppose you are entering sales
amounts into the computer to calculate
extended totals. You want the computer to print
the quantity sold, part number, and extended
total (quantity times the price per unit), as the
following program does.
#include <iostream.h>
#include <iomanip.h>
int main()
{
int part_no, quantity;
float cost, ext_cost;
cout << “*** Inventory Computation ***\n\n”; // Title
// Get inventory information.
do
{ cout << “What is the next part number (-999 to end)? “;
cin >> part_no;
if (part_no != -999)
{ cout << “How many were bought? “;
cin >> quantity;
cout << “What is the unit price of this item? “;
cin >> cost;
ext_cost = cost * quantity;
cout << “\n” << quantity << “ of # “ << part_no <<
“ will cost “ << setprecision(2) <<
ext_cost;
cout << “\n\n\n”; // Print two blank lines.
}
} while (part_no != -999); // Loop only if part
// number is not -999.
cout << “End of inventory computation\n”;
return 0;
}
 The do-while loop controls the entry of the
customer sales information.

 Notice the “trigger” that ends the loop.

 If the user enters –999 for the part number, the


do-while loop quits because no part numbered
–999 exists in the inventory.
 Example3: using a do…while to computes a sum of
consecutive integers.
#include<iostream>
int main( )
{ int n, I =1;
iout<< “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<<endl;
}
 C++ provides the exit() function as a way to leave
a program early (before its natural finish). The
format of exit () is

exit (status);

Check relevant materials to


read more about it!!!
 Thefor loop enables you to repeat sections of your
program for a specific number of times.

 Unlikethe while and do-while loops, the for loop is


a determinate loop.

 This means when you write your program you can


usually determine how many times the loop
iterates.

 Thewhile and do-while loops repeat only until a


condition is met.
 The for statement encloses one or more C++
statements that form the body of the loop.

 These statements in the loop continuously repeat for


a specified number of times.

 The format of the for loop is


for (start expression; test expression; count expression)
{
Block of one or more C++ statements;
}
 This section focuses on the for loop construct
by introducing

 The for statement


 Nested for loops

 The for loop is a helpful way of looping


through a section of code when you want to
count, or sum , specified amounts
 but it does not replace the while and do-while
loops.
 C++ evaluates the start expression before the loop
begins.
 the start expression is an assignment statement

(such as ctr=1;)
 C++ evaluates start expression only once, at the top

of the loop.
 Every time the body of the loop repeats,
 the count expression executes,
 usually incrementing or decrementing a variable.
 The test expression evaluates to True (nonzero) or

False (zero),
 then determines whether the body of the loop

repeats again.
 Example1: To give you a glimpse of the for loop’s
capabilities, this example shows you two programs:
one that uses a for loop and one that does not. The
first one is a counting program.
 Beforestudying its contents, look at the output.
The results illustrate the for loop concept very well.

 Identify the program and include the necessary


header file. You need a counter, so make ctr an
integer variable.
 1. Add one to the counter.
 2. If the counter is less than or equal to 10, print its

value and repeat step one.


 The program with a for loop follows:
// introduces the for loop.
#include <iostream.h>
main()
{
int ctr;
for (ctr=1; ctr<=10; ctr++) // Start ctr at one.
// Increment through loop.
{ cout << ctr << “\n”; } // Body of for loop.
return 0;
}
 Example2: Both of the following sample
programs add the numbers from 100 to 200.
The first one uses a for loop; the second one
does not. The first example starts with a start
expression bigger than 1, thus starting the loop
with a bigger counts expression as well.

 This program has a for loop:


// Demonstrates totaling using a for loop.
#include <iostream.h>
int main()
{
int total, ctr;
total = 0; // Holds a total of 100 to 200.
for (ctr=100; ctr<=200; ctr++) // ctr is 100, 101,
// 102,...200
{ total += ctr; } // Add value of ctr to each iteration.
cout << “The total is “ << total << “\n”;
return 0;
}
// Prints the even numbers from 1 to 20,
// then the odd numbers from 1 to 20.
#include <iostream.h>
int main()
{
int num; // The for loop variable
cout << “Even numbers below 21\n”; // Title
for (num=2; num<=20; num+=2)
{ cout << num << “ “; } // Prints every other number.
cout << “\nOdd numbers below 20\n”; // A second title
for (num=1; num<=20; num+=2)
{ cout << num << “ “; } // Prints every other number.
return 0;
}
 Example4: You can decrement the loop variable as well. If
you do, the value is subtracted from the loop variable each time
through the loop.
 The following example is a rewrite of the counting program. It
produces the reverse effect by showing a countdown.
 // Countdown to the liftoff.
 #include <iostream.h>
 int main()
 {
 int ctr;
 for (ctr=10; ctr!=0; ctr--)
 { cout << ctr << “\n”; } // Print ctr as it
 // counts down.
 cout << “*** Blast off! ***\n”;
 return 0;
Any C++ statement can go inside the body of a for loop—
even another for loop! When you put a loop in a loop, you are
creating a nested loop
Example: this program prints a multiplication table;
#include<iostream>
#include<iomanip>
Int main()
{
for (int x=1; x<=12; x++)
{
for(int y=1; y<=12; y++)
Cout<<setw(4)<<x*y;
Cout<<endl;
}
}

You might also like