2_5271885245589774822 (1)
2_5271885245589774822 (1)
2_5271885245589774822 (1)
Chapter SIX
LOOPS
In the code above example, condition is any expression that returns a Boolean result
– true or false. It determines how long the loop body will be repeated and is called the
loop condition. In this example the loop body is the programming code executed at each
iteration of the loop, i.e. whenever the input condition is true. The behavior of while loops
can be represented by the following scheme:
1
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
In the while loop, first of all the Boolean expression is calculated and if it is true the
sequence of operations in the body of the loop is executed.
Then again the input condition is checked and if it is true again the body of the loop is
executed.
All this is repeated again and again until at some point the conditional expression
returns value false. At this point the loop stops and the program continues to the next line,
immediately after the body of the loop.
The body of the while loop may not be executed even once if in the beginning the
condition of the cycle returns false. If the condition of the cycle is never broken the loop
will be executed indefinitely.
2
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
Let’s give some more examples in order to illustrate the usefulness of loops and to show
some problems that can be solved by using loops.
3
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
First, we initialize the variables num and sum with the value of 1.
In num we keep the current number, which we add to the sum of the preceding
numbers. Trough each loop we increase num with 1 to get the next number, then in the
condition of the loop we check whether it is in the range from 1 to n.
The sum variable contains the sum of the numbers from 1 to num at any time. Upon
entering the loop we add to sum the next number stored in num.
We print on the console all num numbers from 1 to n with a separator "+" and the final
result of the summing after the loop’s ending.
The result of the program’s execution is as follows (we enter n = 17):
4
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
We use the variable divider to store the value of a potential divisor of the number.
First, we initialize it with 2 (the smallest possible divider).
The variable maxDivider is the maximum possible divisor, which is equal to the square
root of the number.
If we have a divisor bigger than √num, then num should also have another divisor
smaller than √num and that’s why it’s useless to check the numbers bigger than √num.
This way we reduce the number of loop iterations.
For the result we use a Boolean variable called prime.
5
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
Initially, its value is true. While passing through the loop, if it turns out that the number
has a divisor, the value of prime will become false.
The condition of the while loop consists of two other sub-conditions which are related
to the logical operator (logical and).
In order to execute the loop, these two sub-conditions must be true simultaneously.
If at some point we find a divisor of the number num, the variable prime becomes false
and the condition of the loop is no longer satisfied.
This means that the loop is executed until it finds the first divisor of the number or until
it proves the fact that num is not divisible by any of the numbers in the range from 2 to
√num.
Here is how the result of the above example’s execution looks like if the input values
are respectively the numbers 37 and 34:
6
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
Let’s remember from the mathematics what is factorial and how it is calculated. The
factorial of an integer n is a function that is calculated as a product of all integers less than
or equal to n or equal to it.
It is written down as n! and by definition the following formulas are valid for it:
First, we initialize the variable factorial with 1 and read n from the console.
We construct an endless while loop by using true as a condition of the loop.
7
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
We use the break operator, in order to terminate the loop, when n reaches a value less
than or equal to 1. Otherwise, we multiply the current result by n and we reduce n with one
unit.
Practically in the first iteration of the loop the variable factorial has a value n, in the
second – n*(n-1) and so on. In the last iteration of the loop the value of factorial is the
product n*(n-1)*(n-2)*…*3*2, which is the desired value of n!.
If we execute the sample program and enter 10 as input, we obtain the following result:
8
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
At the beginning we start with a result of 1 and multiply consecutively the result at each
iteration by n, and reduce n by one unit, until n reaches 0.
This gives us the product n*(n-1)*…*1. Finally, we print the result on the console. This
algorithm always performs at least one multiplication and that’s why it will not work
properly when n ≤ 0.
Here is the result of the above example’s execution for n=7:
9
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
They contain an initialization block (A), condition (B), body (D) and updating
commands for the loop variables (C).
We will explain them in details shortly. Before that, let’s look at how the program code
of a for-loop looks like:
10
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
It consists of an initialization part for the counter (in the pattern int i = 0), a Boolean
condition (i < 10), an expression for updating the counter (i++, it might be i-- or for
instance, i = i + 3) and body of the loop.
The counter of the loop distinguishes it from other types of loops. Most often the
counter changes from a given initial value to a final one in ascending order, for example
from 1 to 100. The number of iterations of a given for-loop is usually known before its
execution starts.
Initialization of For Loops
For-loops can have an initialization block:
It is executed only once, just before entering the loop. Usually the initialization block
is used to declare the counter-variable (also called a loop variable) and to set its initial
value. This variable is "visible" and can be used only within the loop. In the initialization
block is possible to declare and initialize more than one variable.
11
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
The condition (loop condition) is evaluated once before each iteration of the loop, just
like in the while loops. For result true the loop’s body is executed, for result false it is
skipped and the loop ends (the program continues immediately after the last line of the
loop’s body).
This code is executed at each iteration, after the loop’s body has been executed. It is
most commonly used to update the value of the counter-variable.
For-Loop – Example
Here is a complete example of a for-loop:
12
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
13
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
First, we initialize the result (result = 1). The loop starts by setting an initial value for
the counter-variable (int i = 0).
We define the condition for the loop’s execution (i < m).
This way the loop will be executed from 0 to m-1 i.e. exactly m times.
During each run of the loop we multiply the result by n and so n will be raised to the
next power (1, 2, …, m) at each iteration.
Finally, we print the result to see if the program works properly.
Here is how the outcome of the program for n = 2 and m = 10 looks like:
14
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
The condition for loop termination is overlapping of the counters. Finally, we get the
following result:
Operator "continue"
The continue operator stops the current iteration of the inner loop, without terminating
the loop. With the following example we will examine how to use this operator.
We will calculate the sum of all odd integers in the range [1…n], which are not divisible
by 7 by using the for-loop:
15
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
First, we initialize the loop’s variable with a value of 1 as this is the first odd integer
within the range [1…n].
After each iteration of the loop we check if i has not yet exceeded n (i <= n).
In the expression for updating the variable we increase it by 2 in order to pass only
through the odd numbers.
Inside the loop body we check whether the current number is divisible by 7.
If so, we call the operator continue, which skips the rest of the loop’s body (it skips
adding the current number to the sum).
If the number is not divisible by seven, it continues with updating of the sum with the
current number.
The result of the example for n = 11 is as follows:
16
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman
After initialization of the first for loop, the execution of its body will start, which
contains the second (nested) loop.
Its variable will be initialized, its condition will be checked and the code within its body
will be executed, then the variable will be updated and execution will continue until the
condition returns false.
After that the second iteration of the first for loop will continue, its variable will be
updated and the whole second loop will be performed once again. The inner loop will be
fully executed as many times as the body of the outer loop.
17