execute blocks of code multiple times svetlin nakov · 06-01-2019 · what is loop? a loop is a...
TRANSCRIPT
LoopsLoopsExecute Blocks of Code Multiple TimesExecute Blocks of Code Multiple Times
Svetlin NakovSvetlin NakovTelerik CorporationTelerik Corporationwww.telerik.comwww.telerik.com
Table of ContentsTable of Contents
What is a Loop?What is a Loop? Loops in C#Loops in C#
whilewhile loops loops
dodo … … whilewhile loops loops
forfor loops loops
foreachforeach loops loops
Nested loopsNested loops
What Is Loop?What Is Loop? A A looploop is a control statement that allows is 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 condition May execute a code block while given condition holdsholds
May execute a code block for each member of a May execute a code block for each member of a collectioncollection
Loops that never end are called an Loops that never end are called an infinite infinite loopsloops
Using Using while(…)while(…) Loop LoopRepeating a Statement While Repeating a Statement While
Given Condition HoldsGiven Condition Holds
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 of Returns a boolean result of truetrue or or falsefalse
Also called Also called loop conditionloop condition
while (condition)while (condition){{ statements;statements;}}
While Loop – How It Works?While Loop – How It Works?
truetrue
conditioncondition
statementstatement
falsefalse
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++;}}
while(…)while(…)ExamplesExamples
Sum 1..N – ExampleSum 1..N – Example Calculate and print the sum of the first N Calculate and print the sum of the first N
natural numbersnatural numbersConsole.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);
Calculating Sum 1..NCalculating Sum 1..NLive DemoLive Demo
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);
Checking Whether a Checking Whether a Number Is PrimeNumber Is Prime
Live DemoLive Demo
Using Using breakbreak Operator Operator breakbreak operator exits the inner-most loop operator exits the inner-most loop
static void Main()static void Main(){{ int n = Convert.ToInt32(Console.ReadLine());int n = Convert.ToInt32(Console.ReadLine()); // Calculate n! = 1 * 2 * ... * n// Calculate n! = 1 * 2 * ... * n int result = 1;int result = 1; while (true)while (true) {{ if(n == 1)if(n == 1) break;break; result *= n;result *= n; n--;n--; }} Console.WriteLine("n! = " + result); Console.WriteLine("n! = " + result); }}
Calculating FactorialCalculating FactorialLive DemoLive Demo
dodo { { … … }} while while ((……))
LoopLoop
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);
Do-While StatementDo-While Statement
truetrue
conditioncondition
statementstatement
falsefalse
dodo { { … … }} while while ((……))
ExamplesExamples
Factorial – ExampleFactorial – Example
Calculating N factorialCalculating N factorialstatic void Main()static void Main(){{ int n = Convert.ToInt32(Console.ReadLine());int n = Convert.ToInt32(Console.ReadLine()); int factorial = 1;int factorial = 1;
dodo {{ factorial *= n;factorial *= n; n--;n--; }} while (n > 0);while (n > 0);
Console.WriteLine("n! = " + factorial);Console.WriteLine("n! = " + factorial);}}
Factorial with Factorial with BigIntegerBigInteger – – ExampleExample
Calculating N factorialCalculating N factorial with with BigIntegerBigInteger
using System.Numerics;using System.Numerics;static void Main()static void Main(){{ int n = 1000;int n = 1000; BigIntegerBigInteger factorial = 1; factorial = 1; dodo {{ factorial *= n;factorial *= n; n--;n--; }} while (n > 0);while (n > 0); Console.WriteLine("n! = " + factorial);Console.WriteLine("n! = " + factorial);}}
Don't forget to add Don't forget to add reference to reference to
System.Numerics.dlSystem.Numerics.dlll..
Factorial (Factorial (dodo ... ... whilewhile))Live DemoLive Demo
Product[N..M] – ExampleProduct[N..M] – Example
Calculating the product of all numbers in the Calculating 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);
Product of the Numbers Product of the Numbers in the Interval [n..m]in the Interval [n..m]
Live DemoLive Demo
forfor Loops Loops
For LoopsFor Loops
The typical The 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;}}
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
The Test ExpressionThe Test Expression
Evaluated before each iteration of the loopEvaluated before each iteration of the loop
If If truetrue, the loop body is executed, the loop body is executed
If If falsefalse, the loop body is skipped, the loop body is skipped
Used as a Used 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
The Update ExpressionThe Update Expression
Executed at each iteration Executed at each iteration afterafter the body of the 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
forfor Loop LoopExamplesExamples
Simple Simple forfor Loop – Example Loop – Example A simple for-loop to print the numbers A 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;}}
Complex Complex forfor Loop – Example Loop – Example
31
Complex Complex 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=1i=2, sum=3i=2, sum=3i=4, sum=7i=4, sum=7i=8, sum=15i=8, sum=15......
Result:Result:
For LoopsFor LoopsLive DemoLive Demo
N^M – ExampleN^M – Example Calculating Calculating nn to power to 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);}}
Calculating N^MCalculating N^MLive DemoLive Demo
Using Using continuecontinue Operator Operator continuecontinue operator ends the iteration of the operator ends the iteration of the
inner-most loopinner-most loop Example: sum all odd numbers in Example: sum all odd numbers in [1,[1, n]n]
that are not divisors of that 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);
Using Using continuecontinue Operator OperatorLive DemoLive Demo
foreachforeach Loop LoopIteration over a CollectionIteration over a Collection
For LoopsFor Loops
The typical The typical foreachforeach loop syntax is: loop syntax is:
Iterates over all elements of a collectionIterates over all elements of a collection
The The elementelement is the loop variable that takes is the loop variable that takes sequentially all collection valuessequentially all collection values
The The collectioncollection can be list, array or other can 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;}}
foreachforeach Loop – Example Loop – Example
Example of Example 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 variable The variable dayday takes all its values takes all its values
foreachforeach Loop LoopLive DemoLive Demo
Nested LoopsNested LoopsUsing Loops Inside a LoopUsing Loops Inside a Loop
What Is Nested Loop?What Is Nested Loop? A composition of loops is called a A 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; }} … …} }
Nested LoopsNested LoopsExamplesExamples
Triangle – ExampleTriangle – Example Print the following triangle:Print the following triangle:
11
1 21 2
……
1 2 3 ... n1 2 3 ... n
int n = int.Parse(Console.ReadLine());int n = int.Parse(Console.ReadLine());for(int row = 1; row <= n; row++)for(int row = 1; row <= n; row++){{ for(int column = 1; column <= row; column++)for(int column = 1; column <= row; column++) {{ Console.Write("{0} ", column);Console.Write("{0} ", column); }} Console.WriteLine();Console.WriteLine();}}
TriangleTriangleLive DemoLive Demo
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); }}}}
Primes in Range [n, m]Primes in Range [n, m]Live DemoLive Demo
C# Jump StatementsC# Jump Statements Jump statements are:Jump statements are:
breakbreak, , continuecontinue, , gotogoto
How How continuecontinue woks? woks?
In In whilewhile and and do-whiledo-while loops jumps to the loops jumps to the test expressiontest expression
In In forfor loops jumps to the update expression loops 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 label with a label
Avoid using Avoid using gotogoto! (it is considered harmful)! (it is considered harmful)
C# Jump Statements – ExampleC# Jump Statements – Example
int outerCounter = 0;int outerCounter = 0;for (int outer = 0; outer < 10; outer++)for (int outer = 0; outer < 10; outer++){{ for (int inner = 0; inner < 10; inner++) for (int inner = 0; inner < 10; inner++) {{ if (inner % 3 == 0) if (inner % 3 == 0) continue;continue; if (outer == 7) if (outer == 7) break;break; if (inner + outer > 9) if (inner + outer > 9) goto breakOut;goto breakOut; } } outerCounter++;outerCounter++;}}breakOut:breakOut:
LabelLabel
Loops – More ExamplesLoops – More Examples
Nested Loops – ExamplesNested Loops – Examples Print all four digit numbers in format Print all four digit numbers in format ABCDABCD
such that such 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 improve Can you improve this algorithm to this algorithm to use 3 loops only?use 3 loops only?
Happy NumbersHappy NumbersLive DemoLive Demo
Nested Loops – ExamplesNested Loops – Examples Print all combinations from TOTO 6/49Print all combinations from TOTO 6/49
static void Main()static void Main(){{ int i1, i2, i3, i4, i5, i6;int i1, i2, i3, i4, i5, i6; for (i1 = 1; i1 <= 44; i1++)for (i1 = 1; i1 <= 44; i1++) for (i2 = i1 + 1; i2 <= 45; i2++)for (i2 = i1 + 1; i2 <= 45; i2++) for (i3 = i2 + 1; i3 <= 46; i3++)for (i3 = i2 + 1; i3 <= 46; i3++) for (i4 = i3 + 1; i4 <= 47; i4++)for (i4 = i3 + 1; i4 <= 47; i4++) for (i5 = i4 + 1; i5 <= 48; i5++)for (i5 = i4 + 1; i5 <= 48; i5++) for (i6 = i5 + 1; i6 <= 49; i6++)for (i6 = i5 + 1; i6 <= 49; i6++) Console.WriteLine("{0} {1} {2} {3} {4} {5}",Console.WriteLine("{0} {1} {2} {3} {4} {5}", i1, i2, i3, i4, i5, i6);i1, i2, i3, i4, i5, i6);}}
Warning: Warning: execution of this execution of this code could take code could take too long time.too long time.
TOTO 6/49TOTO 6/49Live DemoLive Demo
SummarySummary C# supports four types of loops:C# supports four types of loops:
whilewhile
do-whiledo-while
forfor loops loops
foreachforeach loops loops
Nested loops can be used to implement more Nested loops can be used to implement more complex logiccomplex logic
The operators The operators continuecontinue,, breakbreak & & gotogoto can can control the loop executioncontrol the loop execution
ExercisesExercises1.1. Write a program that prints all the numbers from 1 Write a program that prints all the numbers from 1
to N.to N.
2.2. Write a program that prints all the numbers from 1 Write a program that prints all the numbers from 1 to N, that are not divisible by 3 and 7 at the same to N, that are not divisible by 3 and 7 at the same time.time.
3.3. Write a program that reads from the console a Write a program that reads from the console a sequence of N integer numbers and returns the sequence 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 N Write 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)! for Write a program that calculates N!*K! / (K-N)! for given N and K (1<N<K).given N and K (1<N<K).
Exercises (2)Exercises (2)1.1. Write a program that, for a given two integer Write a program that, for a given two integer
numbers numbers NN and and XX, calculates the sum, calculates the sumS = 1 + 1!S = 1 + 1!/X/X + + 2!/X2!/X22 + + …… + + N!/XN!/XNN
2.2. Write a program that reads a number N and Write a program that reads a number N and calculates the sum of the first N members of the calculates 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 the Each 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.
4.4. Write a program that calculates the greatest Write a program that calculates the greatest common divisor (GCD) of given two numbers. Use common divisor (GCD) of given two numbers. Use the Euclidean algorithm (find it in Internet).the Euclidean algorithm (find it in Internet).
Exercises (3)Exercises (3)
1.1. In the combinatorial mathematics, the Catalan In 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 Catalan number by given N.number by given N.
5.5. Write a program that prints all possible cards from a Write a program that prints all possible cards from a standard deck of 52 cards (without jokers). The standard deck of 52 cards (without jokers). The cards should be printed with their English names. cards should be printed with their English names. Use nested Use nested forfor loops and loops and switch-caseswitch-case..
Exercises (4)Exercises (4)
60
1.1. Write a program that reads from the console a Write a program that reads from the console a positive integer number N (N < 20) and outputs a positive 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
Exercises (5)Exercises (5)
1.1. * 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 the many trailing zeros present at the end of the number N!. Examples:number N!. Examples:
N = 10 N = 10 N! = 36288 N! = 362880000 2 2
N = 20 N = 20 N! = 243290200817664 N! = 24329020081766400000000 4 4
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 the Hint: The trailing zeros in N! are equal to the number of its prime divisors of value number of its prime divisors of value 55. Think why!. Think why!
61
Exercises (6)Exercises (6)
1.1. * 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 the number N (N < 20) from console and outputs in the console the numbers 1 ... N numbers arranged as a console 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