SlideShare una empresa de Scribd logo
1 de 62
LoopsLoops
Execute Blocks of Code MultipleTimesExecute Blocks of Code MultipleTimes
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
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
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
UsingUsing while(…)while(…) LoopLoop
Repeating a Statement WhileRepeating 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 ofReturns a boolean result of truetrue oror falsefalse
Also calledAlso 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 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);
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 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 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
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 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 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 {{ …… }}
whilewhile ((……))
ExamplesExamples
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);
}}
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..
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 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 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 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
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
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
forfor LoopLoop
ExamplesExamples
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;
}}
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:
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 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^M
Live DemoLive Demo
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);
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 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;
}}
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
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 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 Loops
ExamplesExamples
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();
}}
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 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
 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)
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 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?
Happy NumbersHappy Numbers
Live 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 thisexecution of this
code could takecode could take
too long time.too long time.
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 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
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 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).
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).
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..
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
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
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

Más contenido relacionado

La actualidad más candente

A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleSaúl Ibarra Corretgé
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Ismar Silveira
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014Fantix King 王川
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Sergey Platonov
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)jeffz
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6Vince Vo
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)Olve Maudal
 
Oops pramming with examples
Oops pramming with examplesOops pramming with examples
Oops pramming with examplesSyed Khaleel
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumlercorehard_by
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programmingjeffz
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Platonov Sergey
 
C++ L03-Control Structure
C++ L03-Control StructureC++ L03-Control Structure
C++ L03-Control StructureMohammad Shaker
 

La actualidad más candente (20)

A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4Paradigmas de Linguagens de Programacao - Aula #4
Paradigmas de Linguagens de Programacao - Aula #4
 
C++ programming
C++ programmingC++ programming
C++ programming
 
C# Loops
C# LoopsC# Loops
C# Loops
 
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
About Those Python Async Concurrent Frameworks - Fantix @ OSTC 2014
 
Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >Антон Бикинеев, Writing good std::future&lt; C++ >
Антон Бикинеев, Writing good std::future&lt; C++ >
 
The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)The Evolution of Async-Programming on .NET Platform (TUP, Full)
The Evolution of Async-Programming on .NET Platform (TUP, Full)
 
C++ references
C++ referencesC++ references
C++ references
 
Java căn bản - Chapter6
Java căn bản - Chapter6Java căn bản - Chapter6
Java căn bản - Chapter6
 
C++11 & C++14
C++11 & C++14C++11 & C++14
C++11 & C++14
 
C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)C++ idioms by example (Nov 2008)
C++ idioms by example (Nov 2008)
 
C++ Presentation
C++ PresentationC++ Presentation
C++ Presentation
 
Nested loops
Nested loopsNested loops
Nested loops
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
 
Oops pramming with examples
Oops pramming with examplesOops pramming with examples
Oops pramming with examples
 
C++20 the small things - Timur Doumler
C++20 the small things - Timur DoumlerC++20 the small things - Timur Doumler
C++20 the small things - Timur Doumler
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.Евгений Крутько, Многопоточные вычисления, современный подход.
Евгений Крутько, Многопоточные вычисления, современный подход.
 
C++11
C++11C++11
C++11
 
C++ L03-Control Structure
C++ L03-Control StructureC++ L03-Control Structure
C++ L03-Control Structure
 

Similar a 06 Loops

C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)jahanullah
 
Control structures ii
Control structures ii Control structures ii
Control structures ii Ahmad Idrees
 
1.3 core programming [identify the appropriate method for handling repetition]
1.3 core programming [identify the appropriate method for handling repetition]1.3 core programming [identify the appropriate method for handling repetition]
1.3 core programming [identify the appropriate method for handling repetition]tototo147
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops Hemantha Kulathilake
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loopsbsdeol28
 
Repetition Structure.pptx
Repetition Structure.pptxRepetition Structure.pptx
Repetition Structure.pptxrhiene05
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition StructurePRN USM
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...whileJayfee Ramos
 

Similar a 06 Loops (20)

06.Loops
06.Loops06.Loops
06.Loops
 
Iteration
IterationIteration
Iteration
 
C Sharp Jn (3)
C Sharp Jn (3)C Sharp Jn (3)
C Sharp Jn (3)
 
130707833146508191
130707833146508191130707833146508191
130707833146508191
 
Loops
LoopsLoops
Loops
 
Control structures ii
Control structures ii Control structures ii
Control structures ii
 
Loops (1)
Loops (1)Loops (1)
Loops (1)
 
1.3 core programming [identify the appropriate method for handling repetition]
1.3 core programming [identify the appropriate method for handling repetition]1.3 core programming [identify the appropriate method for handling repetition]
1.3 core programming [identify the appropriate method for handling repetition]
 
Loops c++
Loops c++Loops c++
Loops c++
 
SPL 8 | Loop Statements in C
SPL 8 | Loop Statements in CSPL 8 | Loop Statements in C
SPL 8 | Loop Statements in C
 
COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops COM1407: Program Control Structures – Repetition and Loops
COM1407: Program Control Structures – Repetition and Loops
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
Presentation on nesting of loops
Presentation on nesting of loopsPresentation on nesting of loops
Presentation on nesting of loops
 
Repetition Structure.pptx
Repetition Structure.pptxRepetition Structure.pptx
Repetition Structure.pptx
 
Repetition Structure
Repetition StructureRepetition Structure
Repetition Structure
 
MUST CS101 Lab11
MUST CS101 Lab11 MUST CS101 Lab11
MUST CS101 Lab11
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Java loops for, while and do...while
Java loops   for, while and do...whileJava loops   for, while and do...while
Java loops for, while and do...while
 

Más de maznabili

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solvingmaznabili
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-iimaznabili
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-imaznabili
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principlesmaznabili
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexitymaznabili
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and setsmaznabili
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphsmaznabili
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structuresmaznabili
 
15 Text files
15 Text files15 Text files
15 Text filesmaznabili
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classesmaznabili
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processingmaznabili
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handlingmaznabili
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objectsmaznabili
 
10 Recursion
10 Recursion10 Recursion
10 Recursionmaznabili
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systemsmaznabili
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statementsmaznabili
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-maznabili
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressionsmaznabili
 

Más de maznabili (20)

22 Methodology of problem solving
22 Methodology of problem solving22 Methodology of problem solving
22 Methodology of problem solving
 
21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii21 High-quality programming code construction part-ii
21 High-quality programming code construction part-ii
 
21 high-quality programming code construction part-i
21 high-quality programming code construction part-i21 high-quality programming code construction part-i
21 high-quality programming code construction part-i
 
20 Object-oriented programming principles
20 Object-oriented programming principles20 Object-oriented programming principles
20 Object-oriented programming principles
 
19 Algorithms and complexity
19 Algorithms and complexity19 Algorithms and complexity
19 Algorithms and complexity
 
18 Hash tables and sets
18 Hash tables and sets18 Hash tables and sets
18 Hash tables and sets
 
17 Trees and graphs
17 Trees and graphs17 Trees and graphs
17 Trees and graphs
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
15 Text files
15 Text files15 Text files
15 Text files
 
14 Defining classes
14 Defining classes14 Defining classes
14 Defining classes
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
 
12 Exceptions handling
12 Exceptions handling12 Exceptions handling
12 Exceptions handling
 
11 Using classes and objects
11 Using classes and objects11 Using classes and objects
11 Using classes and objects
 
10 Recursion
10 Recursion10 Recursion
10 Recursion
 
09 Methods
09 Methods09 Methods
09 Methods
 
08 Numeral systems
08 Numeral systems08 Numeral systems
08 Numeral systems
 
07 Arrays
07 Arrays07 Arrays
07 Arrays
 
05 Conditional statements
05 Conditional statements05 Conditional statements
05 Conditional statements
 
04 Console input output-
04 Console input output-04 Console input output-
04 Console input output-
 
03 Operators and expressions
03 Operators and expressions03 Operators and expressions
03 Operators and expressions
 

Último

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Último (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

06 Loops

  • 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
  • 4. UsingUsing while(…)while(…) LoopLoop Repeating a Statement WhileRepeating a Statement While Given Condition HoldsGiven Condition Holds
  • 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);
  • 10. Calculating Sum 1..NCalculating Sum 1..N Live DemoLive Demo
  • 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. Checking Whether aChecking Whether a Number Is PrimeNumber Is Prime Live DemoLive Demo
  • 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); }}
  • 15. dodo {{ …… }} whilewhile ((……)) LoopLoop
  • 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);
  • 18. dodo {{ …… }} whilewhile ((……)) ExamplesExamples
  • 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. 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. Factorial (Factorial (dodo ...... whilewhile)) Live DemoLive Demo
  • 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:
  • 32. For LoopsFor Loops Live DemoLive Demo
  • 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);
  • 37. foreachforeach LoopLoop Iteration over a CollectionIteration over a Collection
  • 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
  • 41. Nested LoopsNested Loops Using Loops Inside a LoopUsing Loops Inside a Loop
  • 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; }} …… }}
  • 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(); }}
  • 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)
  • 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. Loops – More ExamplesLoops – More Examples
  • 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?
  • 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. TOTO 6/49TOTO 6/49 Live DemoLive Demo
  • 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