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

Looping Statements

1. The document discusses different looping constructs in C# including while, do-while, and for loops. It provides examples of calculating sums, checking prime numbers, and calculating factorials using these loops. 2. Nested loops are also mentioned, which are loops placed inside other loops. Key loop concepts like infinite loops, the break and continue operators, and conditional repetition are covered. 3. The goal of the chapter is to help students understand common looping statements in C# and how to develop programs that apply loops to solve problems. Examples are provided to illustrate different ways to define and use loops.

Uploaded by

Kenneth Panopio
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

Looping Statements

1. The document discusses different looping constructs in C# including while, do-while, and for loops. It provides examples of calculating sums, checking prime numbers, and calculating factorials using these loops. 2. Nested loops are also mentioned, which are loops placed inside other loops. Key loop concepts like infinite loops, the break and continue operators, and conditional repetition are covered. 3. The goal of the chapter is to help students understand common looping statements in C# and how to develop programs that apply loops to solve problems. Examples are provided to illustrate different ways to define and use loops.

Uploaded by

Kenneth Panopio
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CHAPTER 6

LOOPING AND ITERATION


Learning Objectives

At the end of this chapter the students would be able to:

1. Know the different looping and iteration statements available in C# Programming


Language;
2. Test C# source codes that implements looping and iteration statements; and
3. Develop C# source codes that applies looping and iteration statements as solution to
different programming problems.

Introduction

In this chapter we will examine the loop and iteration programming constructs through
which we can execute a code snippet repeatedly. We will discuss how to implement conditional
repetitions (while and do-while loops) and how to work with for-loops. We will give examples of
different possibilities to define loops, how to construct them and some of their key usages. Finally,
we will discuss the foreach-loop construct and how we can use multiple loops placed inside each
other (nested loops).

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. Using an infinite loop is rarely needed
except in cases where somewhere in the body of the loop a break operator is used to terminate
its execution prematurely. We will cover this later but now let’s look how to create a loop in the
C# language.

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. A loop’s
termination with the break operator can only be done from its body, during an iteration of the loop.
When break is executed the code in the loop’s body after it is skipped and not executed.

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.
Topic 1: while Loops

One of the simplest and most commonly used loops is while. Below is the format of while
statement loop in C#.

while (condition)
{
loop body;
}
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:

Source: Fundamentals of Computer Programming with C#

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.

while loop examples:

A. 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:
int counter = 0;
while (counter <= 6)
{
Console.WriteLine("Number : " + counter);
counter++;
}

When executing the sample code we obtain the following result:

Number : 0
Number : 1
Number : 2
Number : 3
Number : 4
Number : 5
Number : 6

B. 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:

Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
int num = 1;
int sum = 1;
Console.Write("The sum 1");
while (num < n)
{
num++;
sum += num;
Console.Write(" + " + num);
}
Console.WriteLine(" = " + sum);

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

N = 17
The sum 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 = 153
C. 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:

Console.Write("Enter a positive number: ");


int num = int.Parse(Console.ReadLine());
int divider = 2;
int maxDivider = (int)Math.Sqrt(num);
bool prime = true;
while (prime && (divider <= maxDivider))
{
if (num % divider == 0)
{
prime = false;
}
divider++;
}
Console.WriteLine("Prime? " + prime);

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

Enter a positive number: 37


Prime? True

Enter a positive number: 34


Prime? False
D. 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.
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:

int n = int.Parse(Console.ReadLine());
decimal factorial = 1;
while (true)
{
if (n <= 1)
{
break;
}
factorial *= n;
n--;
}
Console.WriteLine("n! = " + factorial);
Topic 2: 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:

do
{
executable code;
} while (condition);

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

Source: Fundamentals of Computer Programming with C#

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.

do-while loop examples:

A. 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:

Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
decimal factorial = 1;
do
{
factorial *= n;
n--;
} while (n > 0);
Console.WriteLine("n! = " + factorial);

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:

n=7
n! = 5040

B. Let’s give another, more interesting example of working with do-while loops. The goal
is to find the product of all numbers in the range [n…m]. Here is an example solution
to this problem:

Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
Console.Write("m = ");
int m = int.Parse(Console.ReadLine());
int num = n;
long product = 1;
do
{
product *= num;
num++;
} while (num <= m);
Console.WriteLine("product[n...m] = " + product);

In the example code we consecutively assign to num at each iteration the values n,
n+1, …, m and in the variable product we accumulate the product of these values.
We require the user to enter n, which should be less than m. Otherwise we will receive
as a result the number n.

If we run the program for n=2 and m=6 we will obtain the following result:

n=2
m=6
product[n...m] = 720
Topic 3: 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:

Source: Fundamentals of Computer Programming with C#

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:

for (initialization; condition; update)


{
loop's body;
}

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. A for-
loop can have one or several loop variables that move in ascending or descending order or with
a step. It is possible one loop variable to increase and the other – to decrease. It is even possible
to make a loop from 2 to 1024 in steps of multiplication by 2, since the update of the loop variables
can contain not only addition, but any other arithmetic (as well as other) operations.
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.

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.

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.

Since none of the listed elements of the for-loops is mandatory, we can skip them all and
we will get an infinite loop:

for ( ; ; )
{
// Loop body
}

for Loop Examples:

1. Display number 0..10

for (int i = 0; i <= 10; i++)


{
Console.Write(i + " ");
}

The result of its execution is the following:

0 1 2 3 4 5 6 7 8 9 10

2. 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:

for (int i = 1, sum = 1; i <= 128; i = i * 2, sum += i)


{
Console.WriteLine("i={0}, sum={1}", i, sum);
}
The result of this loop’s execution is the following:

i=1, sum=1
i=2, sum=3
i=4, sum=7
i=8, sum=15
i=16, sum=31
i=32, sum=63
i=64, sum=127
i=128, sum=255

3. 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:

Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
Console.Write("m = ");
int m = int.Parse(Console.ReadLine());
decimal result = 1;
for (int i = 0; i < m; i++)
{
result *= n;
}
Console.WriteLine("n^m = " + result);

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:

n=2
m = 10
n^m = 1024

4. 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:

for (int small=1, large=10; small<large; small++, large--)


{
Console.WriteLine(small + " " + large);
}
The condition for loop termination is overlapping of the counters. Finally we get the
following result:

1 10
29
38
47
56

5. 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:

int n = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 1; i <= n; i += 2)
{
if (i % 7 == 0)
{
continue;
}
sum += i;
}
Console.WriteLine("sum = " + sum);

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:

11
sum = 29
Topic 4: foreach Loops

The foreach loop (extended for-loop) is new for the C/C++/C# family of languages, but
is well known for the VB and PHP programmers. This programming construct serves to iterate
over all elements of an array, list or other collection of elements (IEnumerable). It passes
through all the elements of the specified collection even if the collection is not indexed.

Here is how a foreach loop looks like:

foreach (type variable in collection)


{
statements;
}

As we see, it is significantly simpler than the standard for-loop and therefore is very
often preferred by developers because it saves writing when you need to go through all the
elements of a given collection. Here is an example that shows how we can use foreach:

int[] numbers = { 2, 3, 5, 7, 11, 13, 17, 19 };


foreach (int i in numbers)
{
Console.Write(" " + i);
}
Console.WriteLine();
string[] towns = { "London", "Paris", "Milan", "New York" };
foreach (string town in towns)
{
Console. Write(" " + town);
}

In the example we create an array of numbers, which are after that went through with a
foreach loop, and its elements are printed on the console. Then an array of city names (strings)
is created and in the same way it is went through and its elements are printed on the console.
The result of the example is:

2 3 5 7 11 13 17 19
London Paris Milan New York
Topic 5: 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:

for (initialization, verification, update)


{
for (initialization, verification, update)
{
executable code
}

}

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.

Let’s now consider a real example that will demonstrate how useful the nested loops are.

Printing a Triangle – Example

Let’s solve the following problem: for a given number n, to print on the console a triangle
with n number of lines, looking like this:

1
12
123

123…n

We will solve the problem with two for-loops. The outer loop will traverse the lines, and
the inner one – the elements in them. When we are on the first line, we have to print "1" (1 element,
1 iteration of the inner loop). On the second line we have to print "1 2" (2 elements, 2 iterations of
the internal loop). We see that there is a correlation between the line on which we are and the
number of the elements that we print. This tells us how to organize the inner loop’s structure:

- We initialize the loop variable with 1 (the first number that we will print): col = 1;
- The repetition condition depends on the line on which we are: col <= row;
- We increase the loop variable with one unit at each iteration of the internal loop.

Basically, we need to implement a for-loop (external) from 1 to n (for the lines) and put
another for-loop (internal) in it – for the numbers on the current line, which should spin from 1 to
the number of the current line. The external loop should go through the lines while the internal –
through the columns of the current line.
Finally we get the following code:

int n = int.Parse(Console.ReadLine());
for (int row = 1; row <= n; row++)
{
for (int col = 1; col <= row; col++)
{
Console.Write(col + " ");
}
Console.WriteLine();
}

If we execute it, we will make sure that it works correctly. Here is how the result for n=7
looks like:

1
12
123
1234
12345
123456
1234567

You might also like