CSC201 - Week9
CSC201 - Week9
Course Lecturer:
Haruna Musa
([email protected])
Iteration
statements are also called loops
because of their cyclic nature.
The while statement is one of several C++
construct statements.
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.
immediately;
Sum+=i++;
}
Cout<< “the sum of the first”<<n<< “integers
is”<<sum<<endl;
}
This runs as soon as the value I reaches n
exit (status);
(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.