2_5271885245589774822 (1)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Programming Fundamental’s I

Chapter six: LOOPS

DR. ZIED OTHMAN


CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman

Chapter SIX
LOOPS

6.1 What Is a "Loop"?


In programming often requires repeated execution of a sequence of operations. A loop
is a basic programming construct that allows repeated execution of a fragment of source
code. Depending on the type of the loop, the code in it is repeated a fixed number of times
or repeats until a given condition is true (exists).
Loops that never end are called infinite loops.

6.2 While Loops


One of the simplest and most commonly used loops is while.

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.

6.3 Usage of While Loops


Let’s consider a very simple example of using the while loop.
The purpose of the loop is to print on the console the numbers in the range from 0 to 9
in ascending order:

2
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman

When executing the sample code, we obtain the following result:


Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9

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

Ex: Summing the Numbers from 1 to N


In this example we will examine how by using the while loop we can find the sum of
the numbers from 1 to n. The number n is read from the console:

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

Ex: Check If a Number Is Prime


We will write a program to check whether a given number is prime or not.
We will read the number to check from the console. As we know from the mathematics,
a prime number is any positive integer number, which, is not divisible by any other
numbers except 1 and itself.
We can check if the number num is prime when in a loop we check if it divides by
numbers from 2 to √num:

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.4 Operator "break"


The break operator is used for prematurely exiting the loop, before it has completed
its execution in a natural way.
When the loop reaches the break operator it is terminated and the program’s execution
continues from the line immediately after the loop’s body.
Ex: Calculating Factorial
In this example we will calculate the factorial of a number entered from the console.
The calculation is performed by using an infinite while loop and the operator break.

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:

- N! = 1 * 2 * 3 … (n-1) * n, for n> 1;


- 2! = 1 * 2;
- 1! = 1;
- 0! = 1.
The product n! can be expressed by a factorial of integers less than n:
- N! = (N-1)! * N, by using the initial value of 0! = 1.
In order to calculate the factorial of n we will directly use the definition:

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:

6.5 Do-While Loops


The do-while loop is similar to the while loop, but it checks the condition after each
execution of its loop body. This type of loops is called loops with condition at the end
(post-test loop). A do-while loop looks like this:

By design do-while loops are executed according to the following scheme:

8
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman

Initially the loop body is executed. Then its condition is checked.


If it is true, the loop’s body is repeated, otherwise the loop ends.
This logic is repeated until the condition of the loop is broken.
The body of the loop is executed at least once.
If the loop’s condition is constantly true, the loop never ends.

6.6 Usage of Do-While Loops


The do-while loop is used when we want to guarantee that the sequence of operations
in it will be executed repeatedly and at least once in the beginning of the loop.
Ex: Calculating Factorial
In this example we will again calculate the factorial of a given number n, but this time
instead of an infinite while loop we will use a do-while. The logic is similar to that in the
previous example:

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

6.7 For Loops


For-loops are a slightly more complicated than while and do-while loops but on the
other hand they can solve more complicated tasks with less code.
Here is the scheme describing for-loops:

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.

Condition of the For Loop


For-loops can have a loop condition:

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).

Update of the Loop Variables


The last element of a for-loop contains code that updates the loop variable:

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.

The Body of the Loop


The body of the loop contains a block with source code. The loop variables, declared
in the initialization block of the loop are available in it.

For-Loop – Example
Here is a complete example of a for-loop:

12
CHAPTER SIX: Loops…………………………………………..…………………………..……Dr. Zied Othman

The result of its execution is the following:

Here is another, more complicated example of a for-loop, in which we have two


variables i and sum, that initially have the value of 1, but we update them consecutively at
each iteration of the loop:

The result of this loop’s execution is the following:

Ex: Calculating N^M


As a further example we will write a program that raises the number n to a power of m,
and for this purpose we will use a for-loop:

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:

For-Loop with Several Variables


As we have already seen, in the construct of a for-loop we can use multiple variables at
the same time. Here is an example in which we have two counters. One of the counters
moves up from 1 and the other moves down from 10:

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:

6.8 Nested Loops


The nested loops are programming constructs consisting of several loops located into
each other.
The innermost loop is executed more times, and the outermost – less times.
Let’s see how two nested loops look like:

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy