Top Banner
Loops Loops Execute Blocks of Code Multiple Times Execute Blocks of Code Multiple Times Svetlin Nakov Svetlin Nakov Telerik Telerik Corporation Corporation www.telerik. com
62

06. Loops

May 17, 2015

Download

Technology

Intro C# Book

while Loops
do ... while Loops
for Loops
foreach Loops
Nested Loops
Exercises: Working with Loops and Nested Loops
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 06. Loops

LoopsLoopsExecute Blocks of Code Multiple TimesExecute Blocks of Code Multiple Times

Svetlin NakovSvetlin NakovTelerik Telerik

CorporationCorporationwww.telerik.com

Page 2: 06. Loops

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

Page 3: 06. Loops

What Is Loop?What Is Loop? A A looploop is a control statement that is a control statement that

allows repeating execution of a allows repeating execution of a block of statementsblock of statements May execute a code block fixed May execute a code block fixed

number of timesnumber of times May execute a code block while May execute a code block while

given condition holdsgiven condition holds May execute a code block for each May execute a code block for each

member of a collectionmember of a collection Loops that never end are called an Loops that never end are called an

infinite loopsinfinite loops

Page 4: 06. Loops

Using Using while(…)while(…) LoopLoopRepeating a Statement Repeating a Statement

While Given Condition While Given Condition HoldsHolds

Page 5: 06. Loops

How To Use While How To Use While Loop?Loop?

The simplest and most frequently The simplest and most frequently used loopused 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;}}

Page 6: 06. Loops

While Loop – How It While Loop – How It Works?Works?

truetrue

conditioncondition

statementstatement

falsfalsee

Page 7: 06. Loops

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++;}}

Page 8: 06. Loops

while(…)while(…)ExamplesExamples

Page 9: 06. Loops

Sum 1..N – ExampleSum 1..N – Example Calculate and print the sum of the Calculate and print the sum of the

first N natural numbersfirst N natural 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);

Page 10: 06. Loops

Calculating Sum Calculating Sum 1..N1..N

Live DemoLive Demo

Page 11: 06. Loops

Prime Number – Prime Number – ExampleExample

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

Page 12: 06. Loops

Checking Checking Whether a Whether a Number Is Number Is

PrimePrimeLive DemoLive Demo

Page 13: 06. Loops

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); }}

Page 14: 06. Loops

Calculating Calculating FactorialFactorial

Live DemoLive Demo

Page 15: 06. Loops

dodo { { … … }} while while ((……))

LoopLoop

Page 16: 06. Loops

Using Do-While LoopUsing Do-While Loop

Another loop structure is:Another loop structure is:

The block of statements is The block of statements is repeatedrepeated While the boolean loop condition While the boolean loop condition

holdsholds The loop is executed at least onceThe loop is executed at least once

dodo{{ statements;statements;}}while (condition);while (condition);

Page 17: 06. Loops

Do-While StatementDo-While Statement

truetrue

conditioncondition

statementstatement

falsfalsee

Page 18: 06. Loops

dodo { { … … }} while while ((……))

ExamplesExamples

Page 19: 06. Loops

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);}}

Page 20: 06. Loops

Factorial with Factorial with BigIntegerBigInteger – Example – Example

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 Don't forget to add reference to add reference to System.Numerics.dSystem.Numerics.d

llll..

Page 21: 06. Loops

Factorial (Factorial (dodo ... ... whilewhile))Live DemoLive Demo

Page 22: 06. Loops

Product[N..M] – Product[N..M] – ExampleExample

Calculating the product of all Calculating the product of all numbers in the interval [n..m]: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());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);

Page 23: 06. Loops

Product of the Product of the Numbers in the Numbers in the Interval [n..m]Interval [n..m]

Live DemoLive Demo

Page 24: 06. Loops

forfor Loops Loops

Page 25: 06. 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;}}

Page 26: 06. Loops

The Initialization The Initialization ExpressionExpression

Executed once, just before the loop is Executed once, just before the loop is enteredentered Like it is out of the loop, before itLike it is out of the loop, before it

Usually used to declare a counter Usually used to declare a counter variablevariable

for (for (int number = 0int number = 0; ...; ...); ...; ...){{ // Can use number here // Can use number here}}// Cannot use number here// Cannot use number here

Page 27: 06. Loops

The Test ExpressionThe Test Expression

Evaluated before each iteration of Evaluated before each iteration of the loopthe 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

Page 28: 06. Loops

The Update ExpressionThe Update Expression

Executed at each iteration Executed at each iteration afterafter the body of the loop is finishedthe body of the loop is finished

Usually used to update the Usually used to update the countercounter

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

Page 29: 06. Loops

forfor Loop LoopExamplesExamples

Page 30: 06. Loops

Simple Simple forfor Loop – Loop – ExampleExample

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

Page 31: 06. Loops

Complex Complex forfor Loop – Loop – ExampleExample

31

Complex Complex forfor-loops could have -loops could have several counter variables:several counter 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, Console.WriteLine("i={0}, sum={1}", i, sum);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:

Page 32: 06. Loops

For LoopsFor LoopsLive DemoLive Demo

Page 33: 06. Loops

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);}}

Page 34: 06. Loops

Calculating N^MCalculating N^MLive DemoLive Demo

Page 35: 06. Loops

Using Using continuecontinue OperatorOperator

continuecontinue operator ends the iteration of operator ends the iteration of the inner-most loopthe inner-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);

Page 36: 06. Loops

Using Using continuecontinue OperatorOperator

Live DemoLive Demo

Page 37: 06. Loops

foreachforeach Loop LoopIteration over a CollectionIteration over a Collection

Page 38: 06. Loops

For LoopsFor Loops

The typical The typical foreachforeach loop syntax is: loop syntax is:

Iterates over all elements of a Iterates over all elements of a collectioncollection The The elementelement is the loop variable that is the loop variable that

takes sequentially all collection valuestakes sequentially all collection values The The collectioncollection can be list, array or can be list, array or

other group of elements of the same other group of elements of the same typetype

foreach (Type element in collection)foreach (Type element in collection){{ statements; statements;}}

Page 39: 06. Loops

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 The above loop iterates of the array of daysarray of days The variable The variable dayday takes all its takes all its

valuesvalues

Page 40: 06. Loops

foreachforeach Loop LoopLive DemoLive Demo

Page 41: 06. Loops

Nested LoopsNested LoopsUsing Loops Inside a LoopUsing Loops Inside a Loop

Page 42: 06. Loops

What Is Nested Loop?What Is Nested Loop? A composition of loops is called a A composition of loops is called a nested nested

looploop 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; }} … …} }

Page 43: 06. Loops

Nested LoopsNested LoopsExamplesExamples

Page 44: 06. Loops

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();}}

Page 45: 06. Loops

TriangleTriangleLive DemoLive Demo

Page 46: 06. Loops

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); }}}}

Page 47: 06. Loops

Primes in Range [n, Primes in Range [n, m]m]Live DemoLive Demo

Page 48: 06. Loops

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 loops jumps to the test expressionthe test expression

In In forfor loops jumps to the update loops jumps to the update expressionexpression

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 ! (it is considered harmful)harmful)

Page 49: 06. Loops

C# Jump Statements – C# Jump Statements – ExampleExample

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:

LabeLabell

Page 50: 06. Loops

Loops – More Loops – More ExamplesExamples

Page 51: 06. Loops

Nested Loops – Nested Loops – ExamplesExamples

Print all four digit numbers in Print all four digit numbers in format 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}Console.WriteLine("{0}{1}{2}{3}",{3}", a, b, c, d);a, b, c, d);}}

Can you Can you improve this improve this algorithm to algorithm to use 3 loops use 3 loops

only?only?

Page 52: 06. Loops

Happy NumbersHappy NumbersLive DemoLive Demo

Page 53: 06. Loops

Nested Loops – Nested Loops – ExamplesExamples

Print all combinations from TOTO Print all combinations from TOTO 6/496/49static 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} Console.WriteLine("{0} {1} {2} {3} {4} {5}",{5}", i1, i2, i3, i4, i5, i6);i1, i2, i3, i4, i5, i6);}}

Warning: Warning: execution of execution of

this code this code could take could take too long too long

time.time.

Page 54: 06. Loops

TOTO 6/49TOTO 6/49Live DemoLive Demo

Page 55: 06. Loops

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 Nested loops can be used to implement more complex logicimplement more complex logic

The operators The operators continuecontinue,, breakbreak & & gotogoto can control the loop execution can control the loop execution

Page 56: 06. Loops

QuestionsQuestions??

LoopsLoops

http://academy.telerik.com

Page 57: 06. Loops

ExercisesExercises1.1. Write a program that prints all the Write a program that prints all the

numbers from 1 to N.numbers from 1 to N.

2.2. Write a program that prints all the Write a program that prints all the numbers from 1 to N, that are not numbers from 1 to N, that are not divisible by 3 and 7 at the same time.divisible by 3 and 7 at the same time.

3.3. Write a program that reads from the Write a program that reads from the console a sequence of N integer console a sequence of N integer numbers and returns the minimal and numbers and returns the minimal and maximal of them.maximal of them.

4.4. Write a program that calculates N!/K! for Write a program that calculates N!/K! for given N and K (1<N<K).given N and K (1<N<K).

5.5. Write a program that calculates N!*K! / Write a program that calculates N!*K! / (K-N)! for given N and K (1<N<K).(K-N)! for given N and K (1<N<K).

Page 58: 06. Loops

Exercises (2)Exercises (2)6.6. 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

7.7. 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 calculates the sum of the first N members of the sequence of Fibonacci: the sequence of Fibonacci: 0, 1, 1, 2, 3, 5, 8, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, …13, 21, 34, 55, 89, 144, 233, 377, …

Each member of the Fibonacci sequence (except Each member of the Fibonacci sequence (except the first two) is a sum of the previous two the first two) is a sum of the previous two members.members.

6.6. Write a program that calculates the greatest Write a program that calculates the greatest common divisor (GCD) of given two numbers. common divisor (GCD) of given two numbers. Use the Euclidean algorithm (find it in Use the Euclidean algorithm (find it in Internet).Internet).

Page 59: 06. Loops

Exercises (3)Exercises (3)

10.10. In the combinatorial mathematics, the In the combinatorial mathematics, the Catalan numbers are calculated by the Catalan numbers are calculated by the following formula:following formula:

Write a program to calculate the NWrite a program to calculate the Nthth Catalan number by given N.Catalan number by given N.

11.11. Write a program that prints all possible Write a program that prints all possible cards from a standard deck of 52 cards cards from a standard deck of 52 cards (without jokers). The cards should be (without jokers). The cards should be printed with their English names. Use printed with their English names. Use nested nested forfor loops and loops and switch-caseswitch-case..

Page 60: 06. Loops

Exercises (4)Exercises (4)

60

12.12. Write a program that reads from the Write a program that reads from the console a positive integer number N console a positive integer number N (N < 20) and outputs a matrix like the (N < 20) and outputs a matrix like the following: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

Page 61: 06. Loops

Exercises (5)Exercises (5)

13.13. * Write a program that calculates for * Write a program that calculates for given N how many trailing zeros given N how many trailing zeros present at the end of the number N!. present at the end of the number N!. Examples: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 Does your program work for N = 50 000?000?

Hint: The trailing zeros in N! are equal Hint: The trailing zeros in N! are equal to the number of its prime divisors of to the number of its prime divisors of value value 55. Think why!. Think why!

61

Page 62: 06. Loops

Exercises (6)Exercises (6)

14.14. * Write a program that reads a positive * Write a program that reads a positive integer number N (N < 20) from integer number N (N < 20) from console and outputs in the console the console and outputs in the console the numbers 1 ... N numbers arranged as a 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