Loops: Execute Blocks of Code Multiple Times
Loops: Execute Blocks of Code Multiple Times
Svetlin Nakov
Telerik Corporation
www.telerik.com
Table of Contents
What is a Loop?
Loops in C#
while loops
do … while loops
for loops
foreach loops
Nested loops
A loop What Is Loop?
is a
contr
ol
state
ment
that
allows
repea
ting
execu
tion
of a
Using while(…) Loop
Repeating a Statement While
Given Condition Holds
The How To Use While Loop?
simpl
est
and
while (condition)
{
moststatements;
}
frequ
ently
used
loop
While Loop – How It Works?
false
condition
true
statement
While Loop – Example
int counter = 0;
while (counter < 10)
{
Console.WriteLine("Number : {0}", counter);
counter++;
}
while(…)
Examples
Sum 1..N – Example
Calculate and print the sum of the first N
natural numbers
Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
int number = 1;
int sum = 1;
Console.Write("The sum 1");
while (number < n)
{
number++;
sum += number ;
Console.Write("+{0}", number);
}
Console.WriteLine(" = {0}", sum);
Calculating Sum 1..N
Live Demo
Prime Number – Example
Checking whether a number is prime or not
Console.Write("Enter a positive integer number: ");
uint number = uint.Parse(Console.ReadLine());
uint divider = 2;
uint maxDivider = (uint) Math.Sqrt(number);
bool prime = true;
while (prime && (divider <= maxDivider))
{
if (number % divider == 0)
{
prime = false;
}
divider++;
}
Console.WriteLine("Prime? {0}", prime);
Checking Whether a
Number Is Prime
Live Demo
Using break Operator
break operator exits the inner-most loop
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
// Calculate n! = 1 * 2 * ... * n
int result = 1;
while (true)
{
if(n == 1)
break;
result *= n;
n--;
}
Console.WriteLine("n! = " + result);
}
Calculating Factorial
Live Demo
do { … }
while (…)
Loop
Anoth Using Do-While Loop
er
loop
struct
do
{
ure is:statements;
}
while (condition);
The
block
of
state
Do-While Statement
statement
true
condition
false
do { … }
while (…)
Examples
Factorial – Example
Calculating N factorial
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int factorial = 1;
do
{
factorial *= n;
n--;
}
while (n > 0);
Result:
i=1, sum=1
i=2, sum=3
i=4, sum=7
i=8, sum=15
...
31
For Loops
Live Demo
N^M – Example
Calculating n to power m (denoted as n^m):
static void Main()
{
int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());
decimal result = 1;
for (int i=0; i<m; i++)
{
result *= n;
}
Console.WriteLine("n^m = " + result);
}
Calculating N^M
Live Demo
Using continue Operator
continue operator ends the iteration of the
inner-most loop
Example: sum all odd numbers in [1, n]
that are not divisors of 7:
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 = {0}", sum);
Using continue Operator
Live Demo
foreach Loop
Iteration over a Collection
For Loops
The typical foreach loop syntax is:
foreach (Type element in collection)
{
statements;
}
Questions?
http://academy.telerik.com
Exercises
1. Write a program that prints all the numbers from 1
to N.
2. Write a program that prints all the numbers from 1
to N, that are not divisible by 3 and 7 at the same
time.
3. Write a program that reads from the console a
sequence of N integer numbers and returns the
minimal and maximal of them.
4. Write a program that calculates N!/K! for given N
and K (1<N<K).
5. Write a program that calculates N!*K! / (K-N)! for
given N and K (1<N<K).
Exercises (2)
6. Write a program that, for a given two integer
numbers N and X, calculates the sum
S = 1 + 1!/X + 2!/X2 + … + N!/XN
7. Write a program that reads a number N and
calculates the sum of the first N members of the
sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
55, 89, 144, 233, 377, …
Each member of the Fibonacci sequence (except the
first two) is a sum of the previous two members.
8. Write a program that calculates the greatest
common divisor (GCD) of given two numbers. Use
the Euclidean algorithm (find it in Internet).
10. In Exercises (3)
the
comb
inato
rial
math
emat
ics,
the
Catal
an
num
bers
are
calcul
Exercises (4)
12. Write a program that reads from the console a
positive integer number N (N < 20) and outputs a
matrix like the following:
N = 3 N = 4
1 2 3 1 2 3 4
2 3 4 2 3 4 5
3 4 5 3 4 5 6
4 5 6 7
60
Exercises (5)
13. * Write a program that calculates for given N how
many trailing zeros present at the end of the
number N!. Examples:
N = 10 N! = 3628800 2
N = 20 N! = 2432902008176640000 4
Does your program work for N = 50 000?
Hint: The trailing zeros in N! are equal to the number
of its prime divisors of value 5. Think why!
61
Exercises (6)
14. * Write a program that reads a positive integer
number N (N < 20) from console and outputs in the
console the numbers 1 ... N numbers arranged as a
spiral.
Example for N = 4
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
62