Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.
LoopsLoops
Execute Blocks of Code MultipleTimesExecute Blocks of Code MultipleTimes
Svetlin NakovSvetlin Nakov
Telerik Cor...
Table of ContentsTable of Contents
 What is a Loop?What is a Loop?
 Loops in C#Loops in C#
 whilewhile loopsloops
 dod...
What Is Loop?What Is Loop?
 AA looploop is a control statement that allowsis a control statement that allows
repeating ex...
UsingUsing while(…)while(…) LoopLoop
Repeating a Statement WhileRepeating a Statement While
Given Condition HoldsGiven Con...
How To Use While Loop?How To Use While Loop?
 The simplest and most frequently used loopThe simplest and most frequently ...
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)
{{
Cons...
while(…)while(…)
ExamplesExamples
Sum 1..N – ExampleSum 1..N – Example
 Calculate and print the sum of the first NCalculate and print the sum of the first ...
Calculating Sum 1..NCalculating Sum 1..N
Live DemoLive Demo
Prime Number – ExamplePrime Number – Example
 Checking whether a number is prime or notChecking whether a number is prime...
Checking Whether aChecking Whether a
Number Is PrimeNumber Is Prime
Live DemoLive Demo
UsingUsing breakbreak OperatorOperator
 breakbreak operator exits the inner-most loopoperator exits the inner-most loop
s...
Calculating FactorialCalculating Factorial
Live DemoLive Demo
dodo {{ …… }}
whilewhile ((……))
LoopLoop
Using Do-While LoopUsing Do-While Loop
 Another loop structure is:Another loop structure is:
 The block of statements is...
Do-While StatementDo-While Statement
truetrue
conditioncondition
statementstatement
falsefalse
dodo {{ …… }}
whilewhile ((……))
ExamplesExamples
Factorial – ExampleFactorial – Example
 Calculating N factorialCalculating N factorial
static void Main()static void Main...
Factorial withFactorial with BigIntegerBigInteger ––
ExampleExample
 Calculating N factorialCalculating N factorial withw...
Factorial (Factorial (dodo ...... whilewhile))
Live DemoLive Demo
Product[N..M] – ExampleProduct[N..M] – Example
 Calculating the product of all numbers in theCalculating the product of a...
Product of the NumbersProduct of the Numbers
in the Interval [n..m]in the Interval [n..m]
Live DemoLive Demo
forfor LoopsLoops
For LoopsFor Loops
 The typicalThe typical forfor loop syntax is:loop syntax is:
 Consists ofConsists of
Initialization...
The Initialization ExpressionThe Initialization Expression
 Executed once, just before the loop is enteredExecuted once, ...
The Test ExpressionThe Test Expression
 Evaluated before each iteration of the loopEvaluated before each iteration of the...
The Update ExpressionThe Update Expression
 Executed at each iterationExecuted at each iteration afterafter the body ofth...
forfor LoopLoop
ExamplesExamples
SimpleSimple forfor Loop – ExampleLoop – Example
 A simple for-loop to print the numbersA simple for-loop to print the nu...
ComplexComplex forfor Loop – ExampleLoop – Example
31
 ComplexComplex forfor-loops could have several counter-loops could...
For LoopsFor Loops
Live DemoLive Demo
N^M – ExampleN^M – Example
 CalculatingCalculating nn to powerto power mm (denoted as(denoted as n^mn^m):):
static void M...
Calculating N^MCalculating N^M
Live DemoLive Demo
UsingUsing continuecontinue OperatorOperator
 continuecontinue operator ends the iteration of theoperator ends the iterat...
UsingUsing continuecontinue OperatorOperator
Live DemoLive Demo
foreachforeach LoopLoop
Iteration over a CollectionIteration over a Collection
For LoopsFor Loops
 The typicalThe typical foreachforeach loop syntax is:loop syntax is:
 Iterates over all elements of ...
foreachforeach Loop – ExampleLoop – Example
 Example ofExample of foreachforeach loop:loop:
string[] days = new string[] ...
foreachforeach LoopLoop
Live DemoLive Demo
Nested LoopsNested Loops
Using Loops Inside a LoopUsing Loops Inside a Loop
What Is Nested Loop?What Is Nested Loop?
 A composition of loops is called aA composition of loops is called a nested loo...
Nested LoopsNested Loops
ExamplesExamples
Triangle – ExampleTriangle – Example
 Print the following triangle:Print the following triangle:
11
1 21 2
……
1 2 3 ... n...
TriangleTriangle
Live DemoLive Demo
Primes[N, M]Primes[N, M] – Example– Example
 Print all prime numbers in the interval [n, m]:Print all prime numbers in th...
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
...
C# Jump Statements – ExampleC# Jump Statements – Example
int outerCounter = 0;int outerCounter = 0;
for (int outer = 0; ou...
Loops – More ExamplesLoops – More Examples
Nested Loops – ExamplesNested Loops – Examples
 Print all four digit numbers in formatPrint all four digit numbers in for...
Happy NumbersHappy Numbers
Live DemoLive Demo
Nested Loops – ExamplesNested Loops – Examples
 Print all combinations from TOTO 6/49Print all combinations from TOTO 6/4...
TOTO 6/49TOTO 6/49
Live DemoLive Demo
SummarySummary
 C# supports four types of loops:C# supports four types of loops:
whilewhile
do-whiledo-while
forfor lo...
Questions?Questions?
LoopsLoops
http://academy.telerik.com
ExercisesExercises
1.1. Write a program that prints all the numbers from 1Write a program that prints all the numbers from...
Exercises (2)Exercises (2)
6.6. Write a program that, for a given two integerWrite a program that, for a given two integer...
Exercises (3)Exercises (3)
10.10. In the combinatorial mathematics, the CatalanIn the combinatorial mathematics, the Catal...
Exercises (4)Exercises (4)
60
12.12. Write a program that reads from the console aWrite a program that reads from the cons...
Exercises (5)Exercises (5)
13.13. * Write a program that calculates for given N how* Write a program that calculates for g...
Exercises (6)Exercises (6)
14.14. * Write a program that reads a positive integer* Write a program that reads a positive i...
Upcoming SlideShare
Loading in …5
×

06 Loops

385 views

Published on

Loops

Published in: Technology
  • Be the first to comment

  • Be the first to like this

06 Loops

  1. 1. LoopsLoops Execute Blocks of Code MultipleTimesExecute Blocks of Code MultipleTimes Svetlin NakovSvetlin Nakov Telerik CorporationTelerik Corporation www.telerik.comwww.telerik.com
  2. 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. 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
  4. 4. UsingUsing while(…)while(…) LoopLoop Repeating a Statement WhileRepeating a Statement While Given Condition HoldsGiven Condition Holds
  5. 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. 6. While Loop – How It Works?While Loop – How It Works? truetrue conditioncondition statementstatement falsefalse
  7. 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++; }}
  8. 8. while(…)while(…) ExamplesExamples
  9. 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);
  10. 10. Calculating Sum 1..NCalculating Sum 1..N Live DemoLive Demo
  11. 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);
  12. 12. Checking Whether aChecking Whether a Number Is PrimeNumber Is Prime Live DemoLive Demo
  13. 13. UsingUsing breakbreak OperatorOperator  breakbreak operator exits the inner-most loopoperator 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); }}
  14. 14. Calculating FactorialCalculating Factorial Live DemoLive Demo
  15. 15. dodo {{ …… }} whilewhile ((……)) LoopLoop
  16. 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);
  17. 17. Do-While StatementDo-While Statement truetrue conditioncondition statementstatement falsefalse
  18. 18. dodo {{ …… }} whilewhile ((……)) ExamplesExamples
  19. 19. Factorial – ExampleFactorial – Example  Calculating N factorialCalculating N factorial static 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); }}
  20. 20. Factorial withFactorial with BigIntegerBigInteger –– ExampleExample  Calculating N factorialCalculating N factorial withwith 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 addDon't forget to add reference toreference to System.Numerics.dlSystem.Numerics.dl ll..
  21. 21. Factorial (Factorial (dodo ...... whilewhile)) Live DemoLive Demo
  22. 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. 23. Product of the NumbersProduct of the Numbers in the Interval [n..m]in the Interval [n..m] Live DemoLive Demo
  24. 24. forfor LoopsLoops
  25. 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. 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. 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. 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
  29. 29. forfor LoopLoop ExamplesExamples
  30. 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. 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:
  32. 32. For LoopsFor Loops Live DemoLive Demo
  33. 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); }}
  34. 34. Calculating N^MCalculating N^M Live DemoLive Demo
  35. 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);
  36. 36. UsingUsing continuecontinue OperatorOperator Live DemoLive Demo
  37. 37. foreachforeach LoopLoop Iteration over a CollectionIteration over a Collection
  38. 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. 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
  40. 40. foreachforeach LoopLoop Live DemoLive Demo
  41. 41. Nested LoopsNested Loops Using Loops Inside a LoopUsing Loops Inside a Loop
  42. 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; }} …… }}
  43. 43. Nested LoopsNested Loops ExamplesExamples
  44. 44. 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(); }}
  45. 45. TriangleTriangle Live DemoLive Demo
  46. 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. 47. Primes in Range [n, m]Primes in Range [n, m] Live DemoLive Demo
  48. 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)
  49. 49. 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
  50. 50. Loops – More ExamplesLoops – More Examples
  51. 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?
  52. 52. Happy NumbersHappy Numbers Live DemoLive Demo
  53. 53. 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 thisexecution of this code could takecode could take too long time.too long time.
  54. 54. TOTO 6/49TOTO 6/49 Live DemoLive Demo
  55. 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
  56. 56. Questions?Questions? LoopsLoops http://academy.telerik.com
  57. 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. 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. 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. 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. 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. 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

×