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

Loops Handouts

Loops allow code to be repeatedly executed. The main loop types in C# are for, while, and do-while loops. For loops use an initialization, condition, and increment/decrement to control the loop. While loops check a condition before each iteration. Do-while loops check the condition after each iteration, guaranteeing the body runs at least once. Loops are useful for tasks like summing ranges of numbers, finding factors of numbers, and processing unknown quantities of input. Sample problems demonstrate using loops to print number sequences, find minimums/maximums, and calculate factorials.

Uploaded by

A.R ENTERTAIN
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views

Loops Handouts

Loops allow code to be repeatedly executed. The main loop types in C# are for, while, and do-while loops. For loops use an initialization, condition, and increment/decrement to control the loop. While loops check a condition before each iteration. Do-while loops check the condition after each iteration, guaranteeing the body runs at least once. Loops are useful for tasks like summing ranges of numbers, finding factors of numbers, and processing unknown quantities of input. Sample problems demonstrate using loops to print number sequences, find minimums/maximums, and calculate factorials.

Uploaded by

A.R ENTERTAIN
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Loops

Programming constructs through which we can execute a code snippet repeatedly.


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.

C# for Loop
The for keyword indicates a loop in C#. The for loop executes a block of statements repeatedly
until the specified condition returns false.
for(variable initialization; condition; steps)
{
//execute this code block as long as condition is satisfied
}
for (A ; B; C)
{
D;
}
contain an initialization block (A), condition (B), body (D) and updating commands for the loop variables (C).

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.

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

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:

The condition (loop condition) is evaluated once before each iteration of the loop. 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:

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

The result of its execution is the following: 0 1

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:

Calculating N^M – Example


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

Program to find factorial of any number


int n = int.Parse(Console.ReadLine());
// "decimal" is the biggest C# type that can hold integer values
decimal factorial = 1;
// Perform an "infinite loop"
for(int i=n;i>=1;i--)
{
factorial *= i;
}
Console.WriteLine("n! = " + factorial);

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. 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. We will demonstrate exiting from loop with break with an example.

for(int a=10;a<20;a++)
{

if (a > 15) {
/* terminate the loop using break statement */
break;
}
Console.WriteLine("value of a: {0}", a);
}

Operator "continue"
The continue operator stops the current iteration of the inner loop, without terminating the loop.
Calculate the sum of all odd integers in the range [1…n], which are not divisible by 7 by using the for-loop:

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:

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

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.

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:
Check If a Number Is Prime – Example
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. 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.

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:

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.

Calculating Factorial – Example


Console.Write("enter value for n = ");
int n = int.Parse(Console.ReadLine());
// "decimal" is the biggest C# type that can hold integer values
decimal factorial = 1;
// Perform an "infinite loop"
while(n>0)
{
factorial *= n;
n--;
}

Console.WriteLine("n! = " + factorial);

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.

Calculating Factorial – Example


In this example we will again calculate the factorial of a given number n, but this time instead of while loop we
will use a do-while. The logic is similar to that in the previous example:

Console.Write("enter value for n = ");


int n = int.Parse(Console.ReadLine());
// "decimal" is the biggest C# type that can hold integer values
decimal factorial = 1;
// Perform an "infinite loop"
do
{
factorial *= n;
n--;
}
while(n>0);

Console.WriteLine("n! = " + factorial);

Exercises (using for, while and do while loops)

1. Write a program that prints on the console the numbers from 1 to N. The number N
should be read from the standard input.
2. Write a program that prints on the console the numbers from 1 to N, which are not
divisible by 3 and 7 simultaneously. The number N should be read from the standard
input.
3. Write a program that reads from the console a series of integers and prints the smallest
and largest of them.

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