Lecture 4 Loops
Lecture 4 Loops
no
Loop condition n<=200
yes
Statements inside
Loop triNum = triNum + n
#include<iostream>
using namespace std;
int main ()
{
int n, triNum;
triNum = 0;
1 init_expression
no
5 2 loop_condition
yes
3 Program statement
no
1 2 5 4
yes
for ( n = 1; n <= 200; n = n + 1 ){
3
triNum = triNum + n;
6
How for works
The execution of a for statement proceeds as follows:
1. The initial expression is evaluated first. This expression usually sets a
variable that will be used inside the loop, generally referred to as an index
variable, to some initial value.
2. The looping condition is evaluated. If the condition is not satisfied (the
expression is false – has value 0), the loop is immediately terminated.
Execution continues with the program statement that immediately follows
the loop.
3. The program statement that constitutes the body of the loop is executed.
4. The looping expression is evaluated. This expression is generally used to
change the value of the index variable
5. Return to step 2.
Infinite loops
It’s the task of the programmer to design correctly the algorithms so that
loops end at some moment !
}
Relational operators
Operator Meaning
== Is equal to
!= Is not equal to
< Is less than
<= Is less or equal
> Is greater than
>= Is greater or equal
The relational operators have lower precedence than all arithmetic operators:
a < b + c is evaluated as a < (b + c)
while ( expression ){
program statements . . .
}
int main ()
{
//Statements before loop
int n, triNum;
triNum = 0;
Start
Input number
false
number > 0
true
right_digit = number%10
Print right_digit
End
number = number / 10
Example - while
// Program to reverse the digits of a number
#include <iostream>
using namespace std;
int main ()
{
int number, right_digit;
cout<<"Enter your number"<<endl;
cin>>number;
while ( number != 0 ){
do{
program statements . . .
} Loop with the test
while ( loop_expression ); at the end !
Body is executed
at least once !
statement
yes
loop_expression
no
Which loop to choose ?
Criteria: Who determines looping
Entry-condition loop -> for, while
Exit-condition loop -> do
Similar to the break statement, but it does not make the loop
terminate, just skips to the next iteration
Example - continue statement
#include <iostream>
using namespace std;
int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {
/* If i is equals to 6, continue to next iteration without
printing */
if (i == 6)
continue;
else
cout << i << " "; // otherwise print the value of i
}
return 0;
}
Difference between break and continue