In this chapter we will examine the loop programming constructs through which we can execute a code snippet repeatedly. We will discuss how to implement conditional repetitions (while and do-while loops) and how to work with for-loops. We will give examples of different possibilities to define loops, how to construct them and some of their key usages. Finally, we will discuss the foreach-loop construct and how we can use multiple loops placed inside each other (nested loops).
Katraj ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready For S...
Â
06.Loops
1. Loops
Repeating Code Multiple Times
Svetlin Nakov
Technical Trainer
www.nakov.com
Software University
http://softuni.bg
2. Table of Contents
1. What is a Loop?
2. Loops in C#
ï§ while loops
ï§ do ⊠while loops
ï§ for loops
ï§ foreach loops
3. Special loop operators
ï§ break, continue, goto
4. Nested loops
2
3. Loop: Definition
ï§ A loop is a control statement that repeats the execution of a
block of statements
ï§ May execute a code block fixed number of times
ï§ May execute a code block while given condition holds
ï§ May execute a code block for each member of a collection
ï§ Loops that never end are called an infinite loops
while (condition)
{
statements;
}
3
5. How To Use While Loop?
ï§ The simplest and most frequently used loop
ï§ The repeat condition
ï§ Returns a boolean result of true or false
ï§ Also called loop condition
while (condition)
{
statements;
}
5
9. ï§ Calculate and print the sum of the first N natural numbers
Sum 1..N â Example
Console.Write("n = ");
int n = int.Parse(Console.ReadLine());
int number = 1;
int sum = 1;
Console.Write("The sum 1");
while (number < n)
{
number++;
sum += number ;
Console.Write("+{0}", number);
}
Console.WriteLine(" = {0}", sum);
9
13. Using the break Operator
ï§ The break operator exits the inner-most loop
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
// Calculate n! = 1 * 2 * ... * n
int result = 1;
while (true)
{
if (n == 1)
break;
result *= n;
n--;
}
Console.WriteLine("n! = " + result);
}
13
16. Using Do-While Loop
ï§ Another classical loop structure is:
ï§ The block of statements is repeated
ï§ While the boolean loop condition holds
ï§ The loop is executed at least once
do
{
statements;
}
while (condition);
16
19. Calculating N Factorial â Example
static void Main()
{
string numberAsString = Console.ReadLine();
int n = Convert.ToInt32(numberAsString);
int factorial = 1;
do
{
factorial *= n;
n--;
}
while (n > 0);
Console.WriteLine("n! = " + factorial);
}
19
20. using System.Numerics;
static void Main()
{
int n = 1000;
BigInteger factorial = 1;
do
{
factorial *= n;
n--;
}
while (n > 0);
Console.WriteLine("n! = " + factorial);
}
Don't forget to add a reference to
System.Numerics.dll.
Factorial with BigInteger â Example
20
22. 22
ï§ Calculating the product of all numbers in the interval [n..m]:
Product of Numbers [N..M] â Example
int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());
int number = n;
decimal product = 1;
do
{
product *= number;
number++;
}
while (number <= m);
Console.WriteLine("product[{0}..{1}] = {2}", n, m, product);
25. ï§ The typical for loop syntax is:
ï§ Consists of
ï§ Initialization statement
ï§ Boolean test expression
ï§ Update statement
ï§ Loop body block
For Loops
for (initialization; test; update)
{
statements;
}
25
26. ï§ The initialization expression
ï§ Executed once, just before the loop is entered
ï§ Like it is out of the loop, just before it
ï§ Typically used to declare a counter variable
The Initialization Expression
for (int number = 0; ...; ...)
{
// Can use number here
}
// Cannot use number here (out of scope)
26
27. ï§ The test expression is evaluated before each loop iteration
ï§ If true, the loop body is executed
ï§ If false, the loop finishes (and the loop body is skipped)
ï§ Used as a loop condition
The Test Expression
for (int number = 0; number < 10; ...)
{
// Can use number here
}
// Cannot use number here (out of scope)
27
28. ï§ The update expression
ï§ Executed at each iteration after the body of the loop is finished
ï§ Typically used to update the loop counter
ï§ Can update multiple variables
The Update Expression
for (int number = 0; number < 10; number++)
{
// Can use number here
}
// Cannot use number here (out of scope)
28
30. ï§ A simple for-loop to print the numbers 0âŠ9:
Simple for Loop â Example
for (int number = 0; number < 10; number++)
{
Console.Write(number + " ");
}
ï§ A simple for-loop to calculate n!:
decimal factorial = 1;
for (int i = 1; i <= n; i++)
{
factorial *= i;
}
30
31. 31
ï§ A complex for-loop could have several counter variables:
Complex for Loop â Example
for (int i=1, sum=1; i<=128; i=i*2, sum+=i)
{
Console.WriteLine("i={0}, sum={1}", i, sum);
}
i=1, sum=1
i=2, sum=3
i=4, sum=7
i=8, sum=15
...
ï§ Result:
33. N^M â Example
ï§ Calculating n to power m (denoted as n^m):
static void Main()
{
int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());
decimal result = 1;
for (int i=0; i<m; i++)
{
result *= n;
}
Console.WriteLine("n^m = " + result);
}
33
35. ï§ continue bypasses the iteration of the inner-most loop
ï§ Example: sum all odd numbers in [1âŠn], not divisors of 7:
Using the continue Operator
int n = int.Parse(Console.ReadLine());
int sum = 0;
for (int i = 1; i <= n; i += 2)
{
if (i % 7 == 0)
{
continue;
}
sum += i;
}
Console.WriteLine("sum = {0}", sum);
35
38. ï§ The typical foreach loop syntax is:
ï§ Iterates over all the elements of a collection
ï§ The element is the loop variable that takes sequentially all
collection values
ï§ The collection can be list, array or other group of elements of
the same type
For-Each Loops
foreach (var element in collection)
{
statements;
}
38
39. ï§ Example of foreach loop:
ï§ The loop iterates over the array of day names
ï§ The variable day takes all its values
ï§ Inside a foreach loop we cannot modify the current item
foreach Loop â Example
string[] days = {
"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
foreach (var day in days)
{
Console.WriteLine(day);
}
39
42. ï§ A composition of loops is called a nested loop
ï§ A loop inside another loop
What Is Nested Loop?
for (initialization; test; update)
{
for (initialization; test; update)
{
statements;
}
âŠ
}
42
46. Primes in the Range [N ⊠M] â Example
int n = int.Parse(Console.ReadLine());
int m = int.Parse(Console.ReadLine());
for (int number = n; number <= m; number++)
{
bool prime = true;
int divider = 2;
int maxDivider = Math.Sqrt(number);
while (divider <= maxDivider)
{
if (number % divider == 0)
{
prime = false;
break;
}
divider++;
}
if (prime)
Console.Write("{0} ", number);
}
46
48. C# Jump Statements
ï§ Jump statements are:
ï§ break, continue, goto
ï§ How continue woks?
ï§ In while and do-while loops jumps to the test expression
ï§ In for loops jumps to the update expression
ï§ To exit the most-inner loop use break
ï§ To exit from an outer loop use goto with a label
ï§ Note: avoid using goto! (it is considered harmful)
48
49. C# Jump Statements â Example
int outerCounter = 0;
for (int outer = 0; outer < 10; outer++)
{
for (int inner = 0; inner < 10; inner++)
{
if (inner % 3 == 0)
continue;
if (outer == 7)
break;
if (inner + outer > 9)
goto breakOut;
}
outerCounter++;
}
breakOut:Label
49
51. Nested Loops â Examples
ï§ Print all four digit numbers in format ABCD such that A+B = C+D
(known as happy numbers)
static void Main()
{
for (int a = 1; a <= 9; a++)
for (int b = 0; b <= 9; b++)
for (int c = 0; c <= 9; c++)
for (int d = 0; d <= 9; d++)
if (a + b == c + d)
Console.WriteLine("{0}{1}{2}{3}", a, b, c, d);
}
Can you improve
this algorithm to use
only 3 nested loops?
51
55. 55
ï§ C# supports four types of loops:
ï§ while loops
ï§ do-while loops
ï§ for loops
ï§ foreach loops
ï§ Nested loops are used to implement more complex logic
ï§ The operators continue, break & goto can change the
default loop execution behavior
Summary
57. License
ï§ This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
57
ï§ Attribution: this work may contain portions from
ï§ "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license
ï§ "C# Part I" course by Telerik Academy under CC-BY-NC-SA license
58. Free Trainings @ Software University
ï§ Software University Foundation â softuni.org
ï§ Software University â High-Quality Education,
Profession and Job for Software Developers
ï§ softuni.bg
ï§ Software University @ Facebook
ï§ facebook.com/SoftwareUniversity
ï§ Software University @ YouTube
ï§ youtube.com/SoftwareUniversity
ï§ Software University Forums â forum.softuni.bg
Notas do Editor
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
(c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*