1. LoopsLoops
Execute Blocks of Code MultipleTimesExecute Blocks of Code MultipleTimes
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
2. Table of ContentsTable of Contents
What is a Loop?What is a Loop?
Loops in C#Loops in C#
whilewhile loopsloops
dodo …… whilewhile loopsloops
forfor loopsloops
foreachforeach loopsloops
Nested loopsNested loops
3. What Is Loop?What Is Loop?
AA looploop is a control statement that allowsis a control statement that allows
repeating execution of a block of statementsrepeating execution of a block of statements
May execute a code block fixed number of timesMay execute a code block fixed number of times
May execute a code block while given conditionMay execute a code block while given condition
holdsholds
May execute a code block for each member of aMay execute a code block for each member of a
collectioncollection
Loops that never end are called anLoops that never end are called an infiniteinfinite
loopsloops
5. How To Use While Loop?How To Use While Loop?
The simplest and most frequently used loopThe simplest and most frequently used loop
The repeat conditionThe repeat condition
Returns a boolean result ofReturns a boolean result of truetrue oror falsefalse
Also calledAlso called loop conditionloop condition
while (condition)while (condition)
{{
statements;statements;
}}
6. While Loop – How It Works?While Loop – How It Works?
truetrue
conditioncondition
statementstatement
falsefalse
7. While Loop – ExampleWhile Loop – Example
int counter = 0;int counter = 0;
while (counter < 10)while (counter < 10)
{{
Console.WriteLine("Number : {0}", counter);Console.WriteLine("Number : {0}", counter);
counter++;counter++;
}}
9. Sum 1..N – ExampleSum 1..N – Example
Calculate and print the sum of the first NCalculate and print the sum of the first N
natural numbersnatural numbers
Console.Write("n = ");Console.Write("n = ");
int n = int.Parse(Console.ReadLine());int n = int.Parse(Console.ReadLine());
int number = 1;int number = 1;
int sum = 1;int sum = 1;
Console.Write("The sum 1");Console.Write("The sum 1");
while (number < n)while (number < n)
{{
number++;number++;
sum += number ;sum += number ;
Console.Write("+{0}", number);Console.Write("+{0}", number);
}}
Console.WriteLine(" = {0}", sum);Console.WriteLine(" = {0}", sum);
11. Prime Number – ExamplePrime Number – Example
Checking whether a number is prime or notChecking whether a number is prime or not
Console.Write("Enter a positive integer number: ");Console.Write("Enter a positive integer number: ");
uint number = uint.Parse(Console.ReadLine());uint number = uint.Parse(Console.ReadLine());
uint divider = 2;uint divider = 2;
uint maxDivider = (uint) Math.Sqrt(number);uint maxDivider = (uint) Math.Sqrt(number);
bool prime = true;bool prime = true;
while (prime && (divider <= maxDivider))while (prime && (divider <= maxDivider))
{{
if (number % divider == 0)if (number % divider == 0)
{{
prime = false;prime = false;
}}
divider++;divider++;
}}
Console.WriteLine("Prime? {0}", prime);Console.WriteLine("Prime? {0}", prime);
16. Using Do-While LoopUsing Do-While Loop
Another loop structure is:Another loop structure is:
The block of statements is repeatedThe block of statements is repeated
While the boolean loop condition holdsWhile the boolean loop condition holds
The loop is executed at least onceThe loop is executed at least once
dodo
{{
statements;statements;
}}
while (condition);while (condition);
22. Product[N..M] – ExampleProduct[N..M] – Example
Calculating the product of all numbers in theCalculating the product of all numbers in the
interval [n..m]:interval [n..m]:
int n = int.Parse(Console.ReadLine());int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());int m = int.Parse(Console.ReadLine());
int number = n;int number = n;
decimal product = 1;decimal product = 1;
dodo
{{
product *= number;product *= number;
number++;number++;
}}
while (number <= m);while (number <= m);
Console.WriteLine("product[n..m] = " + product);Console.WriteLine("product[n..m] = " + product);
23. Product of the NumbersProduct of the Numbers
in the Interval [n..m]in the Interval [n..m]
Live DemoLive Demo
25. For LoopsFor Loops
The typicalThe typical forfor loop syntax is:loop syntax is:
Consists ofConsists of
Initialization statementInitialization statement
Boolean test expressionBoolean test expression
Update statementUpdate statement
Loop body blockLoop body block
for (initialization; test; update)for (initialization; test; update)
{{
statements;statements;
}}
26. The Initialization ExpressionThe Initialization Expression
Executed once, just before the loop is enteredExecuted once, just before the loop is entered
Like it is out of the loop, before itLike it is out of the loop, before it
Usually used to declare a counter variableUsually used to declare a counter variable
for (for (int number = 0int number = 0; ...; ...); ...; ...)
{{
// Can use number here// Can use number here
}}
// Cannot use number here// Cannot use number here
27. The Test ExpressionThe Test Expression
Evaluated before each iteration of the loopEvaluated before each iteration of the loop
IfIf truetrue, the loop body is executed, the loop body is executed
IfIf falsefalse, the loop body is skipped, the loop body is skipped
Used as aUsed as a loop conditionloop condition
for (int number = 0;for (int number = 0; number < 10number < 10; ...); ...)
{{
// Can use number here// Can use number here
}}
// Cannot use number here// Cannot use number here
28. The Update ExpressionThe Update Expression
Executed at each iterationExecuted at each iteration afterafter the body ofthe body of
the loop is finishedthe loop is finished
Usually used to update the counterUsually used to update the counter
for (int number = 0; number < 10;for (int number = 0; number < 10; number++number++))
{{
// Can use number here// Can use number here
}}
// Cannot use number here// Cannot use number here
30. SimpleSimple forfor Loop – ExampleLoop – Example
A simple for-loop to print the numbersA simple for-loop to print the numbers 00……99::
for (int number = 0; number < 10; number++)for (int number = 0; number < 10; number++)
{{
Console.Write(number + " ");Console.Write(number + " ");
}}
A simple for-loop to calculate n!:A simple for-loop to calculate n!:
decimal factorial = 1;decimal factorial = 1;
for (int i = 1; i <= n; i++)for (int i = 1; i <= n; i++)
{{
factorial *= i;factorial *= i;
}}
31. ComplexComplex forfor Loop – ExampleLoop – Example
31
ComplexComplex forfor-loops could have several counter-loops could have several counter
variables:variables:
for (int i=1, sum=1; i<=128; i=i*2, sum+=i)for (int i=1, sum=1; i<=128; i=i*2, sum+=i)
{{
Console.WriteLine("i={0}, sum={1}", i, sum);Console.WriteLine("i={0}, sum={1}", i, sum);
}}
i=1, sum=1i=1, sum=1
i=2, sum=3i=2, sum=3
i=4, sum=7i=4, sum=7
i=8, sum=15i=8, sum=15
......
Result:Result:
33. N^M – ExampleN^M – Example
CalculatingCalculating nn to powerto power mm (denoted as(denoted as n^mn^m):):
static void Main()static void Main()
{{
int n = int.Parse(Console.ReadLine());int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());int m = int.Parse(Console.ReadLine());
decimal result = 1;decimal result = 1;
for (int i=0; i<m; i++)for (int i=0; i<m; i++)
{{
result *= n;result *= n;
}}
Console.WriteLine("n^m = " + result);Console.WriteLine("n^m = " + result);
}}
35. UsingUsing continuecontinue OperatorOperator
continuecontinue operator ends the iteration of theoperator ends the iteration of the
inner-most loopinner-most loop
Example: sum all odd numbers inExample: sum all odd numbers in [1,[1, n]n]
that are not divisors ofthat are not divisors of 77::
int n = int.Parse(Console.ReadLine());int n = int.Parse(Console.ReadLine());
int sum = 0;int sum = 0;
for (int i = 1; i <= n; i += 2)for (int i = 1; i <= n; i += 2)
{{
if (i % 7 == 0)if (i % 7 == 0)
{{
continue;continue;
}}
sum += i;sum += i;
}}
Console.WriteLine("sum = {0}", sum);Console.WriteLine("sum = {0}", sum);
38. For LoopsFor Loops
The typicalThe typical foreachforeach loop syntax is:loop syntax is:
Iterates over all elements of a collectionIterates over all elements of a collection
TheThe elementelement is the loop variable that takesis the loop variable that takes
sequentially all collection valuessequentially all collection values
TheThe collectioncollection can be list, array or othercan be list, array or other
group of elements of the same typegroup of elements of the same type
foreach (Type element in collection)foreach (Type element in collection)
{{
statements;statements;
}}
39. foreachforeach Loop – ExampleLoop – Example
Example ofExample of foreachforeach loop:loop:
string[] days = new string[] {string[] days = new string[] {
"Monday", "Tuesday", "Wednesday", "Thursday","Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };"Friday", "Saturday", "Sunday" };
foreach (String day in days)foreach (String day in days)
{{
Console.WriteLine(day);Console.WriteLine(day);
}}
The above loop iterates of the array of daysThe above loop iterates of the array of days
The variableThe variable dayday takes all its valuestakes all its values
42. What Is Nested Loop?What Is Nested Loop?
A composition of loops is called aA composition of loops is called a nested loopnested loop
A loop inside another loopA loop inside another loop
Example:Example:
for (initialization; test; update)for (initialization; test; update)
{{
for (initialization; test; update)for (initialization; test; update)
{{
statements;statements;
}}
……
}}
46. Primes[N, M]Primes[N, M] – Example– Example
Print all prime numbers in the interval [n, m]:Print all prime numbers in the interval [n, m]:
int n = int.Parse(Console.ReadLine());int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());int m = int.Parse(Console.ReadLine());
for (int number = n; number <= m; number++)for (int number = n; number <= m; number++)
{{
bool prime = true;bool prime = true;
int divider = 2;int divider = 2;
int maxDivider = Math.Sqrt(num);int maxDivider = Math.Sqrt(num);
while (divider <= maxDivider)while (divider <= maxDivider)
{{
if (number % divider == 0)if (number % divider == 0)
{{
prime = false;prime = false;
break;break;
}}
divider++;divider++;
}}
if (prime)if (prime)
{{
Console.Write("{0} ", number);Console.Write("{0} ", number);
}}
}}
47. Primes in Range [n, m]Primes in Range [n, m]
Live DemoLive Demo
48. C# Jump StatementsC# Jump Statements
Jump statements are:Jump statements are:
breakbreak,, continuecontinue,, gotogoto
HowHow continuecontinue woks?woks?
InIn whilewhile andand do-whiledo-while loops jumps to theloops jumps to the
test expressiontest expression
InIn forfor loops jumps to the update expressionloops jumps to the update expression
To exit an inner loop useTo exit an inner loop use breakbreak
To exit outer loops useTo exit outer loops use gotogoto with a labelwith a label
Avoid usingAvoid using gotogoto! (it is considered harmful)! (it is considered harmful)
51. Nested Loops – ExamplesNested Loops – Examples
Print all four digit numbers in formatPrint all four digit numbers in format ABCDABCD
such thatsuch that AA++BB == CC++DD (known as happy numbers)(known as happy numbers)
static void Main()static void Main()
{{
for (int a =1 ; a <= 9; a++)for (int a =1 ; a <= 9; a++)
for (int b = 0; b <= 9; b++)for (int b = 0; b <= 9; b++)
for (int c = 0; c <= 9; c++)for (int c = 0; c <= 9; c++)
for (int d = 0; d <= 9; d++)for (int d = 0; d <= 9; d++)
if (a + b == c + d)if (a + b == c + d)
Console.WriteLine("{0}{1}{2}{3}",Console.WriteLine("{0}{1}{2}{3}",
a, b, c, d);a, b, c, d);
}}
Can you improveCan you improve
this algorithm tothis algorithm to
use 3 loops only?use 3 loops only?
55. SummarySummary
C# supports four types of loops:C# supports four types of loops:
whilewhile
do-whiledo-while
forfor loopsloops
foreachforeach loopsloops
Nested loops can be used to implement moreNested loops can be used to implement more
complex logiccomplex logic
The operatorsThe operators continuecontinue,, breakbreak && gotogoto cancan
control the loop executioncontrol the loop execution
57. ExercisesExercises
1.1. Write a program that prints all the numbers from 1Write a program that prints all the numbers from 1
to N.to N.
2.2. Write a program that prints all the numbers from 1Write a program that prints all the numbers from 1
to N, that are not divisible by 3 and 7 at the sameto N, that are not divisible by 3 and 7 at the same
time.time.
3.3. Write a program that reads from the console aWrite a program that reads from the console a
sequence of N integer numbers and returns thesequence of N integer numbers and returns the
minimal and maximal of them.minimal and maximal of them.
4.4. Write a program that calculates N!/K! for given NWrite a program that calculates N!/K! for given N
and K (1<N<K).and K (1<N<K).
5.5. Write a program that calculates N!*K! / (K-N)! forWrite a program that calculates N!*K! / (K-N)! for
given N and K (1<N<K).given N and K (1<N<K).
58. Exercises (2)Exercises (2)
6.6. Write a program that, for a given two integerWrite a program that, for a given two integer
numbersnumbers NN andand XX, calculates the sum, calculates the sum
S = 1 + 1!S = 1 + 1!/X/X ++ 2!/X2!/X22
++ …… ++ N!/XN!/XNN
7.7. Write a program that reads a number N andWrite a program that reads a number N and
calculates the sum of the first N members of thecalculates the sum of the first N members of the
sequence of Fibonacci:sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
55, 89, 144, 233, 377, …55, 89, 144, 233, 377, …
Each member of the Fibonacci sequence (except theEach member of the Fibonacci sequence (except the
first two) is a sum of the previous two members.first two) is a sum of the previous two members.
6.6. Write a program that calculates the greatestWrite a program that calculates the greatest
common divisor (GCD) of given two numbers. Usecommon divisor (GCD) of given two numbers. Use
the Euclidean algorithm (find it in Internet).the Euclidean algorithm (find it in Internet).
59. Exercises (3)Exercises (3)
10.10. In the combinatorial mathematics, the CatalanIn the combinatorial mathematics, the Catalan
numbers are calculated by the following formula:numbers are calculated by the following formula:
Write a program to calculate the NWrite a program to calculate the Nthth
Catalan numberCatalan number
by given N.by given N.
11.11. Write a program that prints all possible cards from aWrite a program that prints all possible cards from a
standard deck of 52 cards (without jokers). Thestandard deck of 52 cards (without jokers). The
cards should be printed with their English names.cards should be printed with their English names.
Use nestedUse nested forfor loops andloops and switch-caseswitch-case..
60. Exercises (4)Exercises (4)
60
12.12. Write a program that reads from the console aWrite a program that reads from the console a
positive integer number N (N < 20) and outputs apositive integer number N (N < 20) and outputs a
matrix like the following:matrix like the following:
N = 3N = 3 N = 4N = 4
11 22 33
22 33 44
33 44 55
11 22 33 44
22 33 44 55
33 44 55 66
44 55 66 77
61. Exercises (5)Exercises (5)
13.13. * Write a program that calculates for given N how* Write a program that calculates for given N how
many trailing zeros present at the end of themany trailing zeros present at the end of the
number N!. Examples:number N!. Examples:
N = 10N = 10 N! = 36288N! = 362880000 22
N = 20N = 20 N! = 243290200817664N! = 24329020081766400000000 44
Does your program work for N = 50 000?Does your program work for N = 50 000?
Hint: The trailing zeros in N! are equal to theHint: The trailing zeros in N! are equal to the
number of its prime divisors of valuenumber of its prime divisors of value 55. Think why!. Think why!
61
62. Exercises (6)Exercises (6)
14.14. * Write a program that reads a positive integer* Write a program that reads a positive integer
number N (N < 20) from console and outputs in thenumber N (N < 20) from console and outputs in the
console the numbers 1 ... N numbers arranged as aconsole the numbers 1 ... N numbers arranged as a
spiral.spiral.
Example for N = 4Example for N = 4
62
11 22 33 44
1212 1313 1414 55
1111 1616 1515 66
1010 99 88 77