0% found this document useful (0 votes)
47 views38 pages

Programming Fundamentals 605116: From Problem Analysis To Program Design 4 Edition

The document provides an overview of loops in C# programming. It defines different types of loops like while, do-while, and for loops. It explains how each loop works through examples and covers nested loops, break and continue statements. Key topics covered include conditional expressions for loops, using loops to iterate over collections with foreach, and avoiding infinite loops.

Uploaded by

Ahmad Alshyyab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views38 pages

Programming Fundamentals 605116: From Problem Analysis To Program Design 4 Edition

The document provides an overview of loops in C# programming. It defines different types of loops like while, do-while, and for loops. It explains how each loop works through examples and covers nested loops, break and continue statements. Key topics covered include conditional expressions for loops, using loops to iterate over collections with foreach, and avoiding infinite loops.

Uploaded by

Ahmad Alshyyab
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Programming Fundamentals

5
605116

ISRA University
Faculty of IT

Textbook
BARBARA DOYLE “C# Programming: From Problem Analysis to Program Design 4th
Edition

Prepared by IT Faculty memebers 1


5 Loops

2
Chapter Objectives
• Learn about conditional expressions that return
Boolean results and those that use the bool data
type
• Examine equality, relational, and logical operators
used with conditional expressions
• Write if selection type statements to include one-
way, two-way, and nested forms
• Learn about and write switch statements

3
What Is Loop?
• A loop is a control statement that allows
repeating 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
Using while(…) Loop
Repeating a Statement While
Given Condition Holds
How To Use While Loop?
while (condition)
•{ The simplest and most frequently used loop
statements;
}
• The repeat condition
– Returns a boolean result of true or false
– Also called loop condition
While Loop – How It Works?

false
condition

true

statement
While Loop – Example
int counter = 0;
while (counter < 10)
{
Console.WriteLine("Number : {0}", counter);
counter++;
}
while(…)
Examples
Sum 1..N – Example
• Calculate and print the sum of the first N natural
numbers
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);
Prime Number – Example
• Checking whether a number is prime or not
Console.Write("Enter a positive integer number: ");
uint number = uint.Parse(Console.ReadLine());
uint divider = 2;
uint maxDivider = (uint) Math.Sqrt(number);
bool prime = true;
while (prime && (divider <= maxDivider))
{
if (number % divider == 0)
{
prime = false;
}
divider++;
}
Console.WriteLine("Prime? {0}", prime);
Using break Operator
• 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);
}
do { … }
while (…)
Loop
Using Do-While Loop
do
•{ Another loop structure is:
statements;
}
while (condition);

• The block of statements is repeated


– While the boolean loop condition holds
• The loop is executed at least once
Do-While Statement

statement
true

condition

false
do { … }
while (…)
Examples
Factorial – Example
• Calculating N factorial
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
int factorial = 1;

do
{
factorial *= n;
n--;
}
while (n > 0);

Console.WriteLine("n! = " + factorial);


}
Product[N..M] – Example
• Calculating the product of all numbers in the
interval [n..m]:
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[n..m] = " + product);
for Loops
For Loops
• The typical for loop syntax is:
for (initialization; test; update)
{
statements;
}
• Consists of
– Initialization statement
– Boolean test expression
– Update statement
– Loop body block
The Initialization Expression
for (int number = 0; ...; ...)
{
// Can use number here
}
// Cannot use number here

• Executed once, just before the loop is entered


– Like it is out of the loop, before it
• Usually used to declare a counter variable
The Test Expression
for (int number = 0; number < 10; ...)
{
// Can use number here
}
// Cannot use number here

• Evaluated before each iteration of the loop


– If true, the loop body is executed
– If false, the loop body is skipped
• Used as a loop condition
The Update Expression
for (int number = 0; number < 10; number++)
{
// Can use number here
}
// Cannot use number here

• Executed at each iteration after the body of the


loop is finished
• Usually used to update the counter
for Loop
Examples
• 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;
}
Complex for Loop – Example
 Complex for-loops could have several counter
variables:
for (int i=1, sum=1; i<=128; i=i*2, sum+=i)
{
Console.WriteLine("i={0}, sum={1}", i, sum);
}

 Result:
i=1, sum=1
i=2, sum=3
i=4, sum=7
i=8, sum=15
...
26
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);
}
Using continue Operator
• continue operator ends the iteration of the inner-
most loop
• Example: sum all odd numbers in [1, n]
that are not divisors of 7:
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);
foreach Loop
Iteration over a Collection
For Loops
• The typical foreach loop syntax is:
foreach (Type element in collection)
{
statements;
}
• Iterates over all 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
foreach Loop – Example
• Example of foreach loop:
string[] days = new string[] {
"Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
foreach (String day in days)
{
Console.WriteLine(day);
}

 The above loop iterates of the array of days


 The variable day takes all its values
Nested Loops
Using Loops Inside a Loop
What Is Nested Loop?
• A composition of loops is called a nested loop
– A loop inside another loop
• Example:

for (initialization; test; update)


{
for (initialization; test; update)
{
statements;
}

}
Nested Loops
Examples
Triangle – Example
• Print the following triangle:
1
1 2

1 2 3 ... n
int n = int.Parse(Console.ReadLine());
for(int row = 1; row <= n; row++)
{
for(int column = 1; column <= row; column++)
{
Console.Write("{0} ", column);
}
Console.WriteLine();
}
Primes[N, M] – Example
• Print all prime numbers in the interval [n, m]:
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(num);
while (divider <= maxDivider)
{
if (number % divider == 0)
{
prime = false;
break;
}
divider++;
}
if (prime)
{
Console.Write("{0} ", number);
}
}
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 an inner loop use break
• To exit outer loops use goto with a label
– Avoid using goto! (it is considered harmful)
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;
Label if (inner + outer > 9)
goto breakOut;
}
outerCounter++;
}
breakOut:

You might also like