LOOPS

Execute Blocks of Code Multiple Times

TABLE OF CONTENTS

  • What is a Loop?
  • Loop types
    • while loops
    • do … while loops
    • for loops
    • for-each loops
  • Special loop operators
    • break, continue
  • Nested loops

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!

While loops

Repeating a Statement while given condition holds.
Evaluate the condition first and then execute the code if the condition is true.

While loops (2)

  • The simples and most frequently used loop
  • The repeat condition
  • Returns a boolean result of true or false
  • Also called loop condition

int n = 1;
while (n < 6)
{
    Console.WriteLine("Current value of n is {0}", n);
    n++;
}
					

Do {...} while loops

Do-While loops (3)

  • The block of statement is repeated, while the boolean loop condition holds
  • The loop is executed at least once

int x = 0;
do
{
    Console.WriteLine(x);
    x++;
} while (x < 5);
					

For loops

For loops (3)


// loop N times
for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}
// nested for loops
for (i = 2; i < 100; i++)
{
  for (j = 2; j <= (i / j); j++)
  if ((i % j) == 0) break; // if factor found, not prime
  if (j > (i / j))
  Console.WriteLine("{0} is prime", i);
}
					

For loops (4)

    Consists of
  • Initialization statement
    • Boolean test expression
    • Update statement
    • Loop body block
  • Executed once, just before the loop is entered. Like it is outside of (before the) the loop.
  • Usually used to declare a counter.

The test expression

  • Evaluated before each iteration of the loop
    • If true, the loop body is executed
    • If false, the loop body is skipped
  • Used as loop condition

The update expression

  • Executed at each iteration after the body of the loop is finished
  • Usually used to update the counter

For-each loops

For-each loops (3)

    Iterates over all elements of a collection
  • The element in the loop variable that takes sequentially all collection values
  • The collection can be list, array or other grouping of elements of the same type

int[] fibarray = new int[] { 0, 1, 1, 2, 3, 5, 8, 13 };
foreach (int element in fibarray)
{
    System.Console.WriteLine(element);
}
						

Special loop operators

Using break statement

    The break statement is C# has the following two usages:
  • When the break statement is encountered inside a loop, the loop is immediately terminated and program control resumes at the next statement following the loop.
  • It can be used to terminate a case in the switch statement

Using continue statement

    The continue statement in C# is jumping statement!
  • It skips the current loop and re-executes the loop with new condition
  • Can be used only inside a loop
  • Continue is a keyword

Nested loops

Nested loops (2)

  • A composition of loops is called a nested loop
  • A loop inside another loop

Summary

    • C# supports four types of loops:
    • while
    • do-while
    • for loops
    • for-each
  • Nested loops can be used to implement more complex logic
  • The operators continue and break can control the loop execution
office@e-dojo.it

EXERCISE

Problem 1: Numbers from 1 to N

Write a program that reads from the console a positive integer N and prints all the numbers from 1 to N inclusive, on a single line, separated by a whitespace.

Input Output
5 1 2 3 4 5
1 1

EXERCISE (2)

Problem 2: Not Divisible Numbers

Write a program that reads from the console a positive integer N and prints all the numbers from 1 to N not divisible by 3 or 7, on a single line, separated by a space.

Input Output
10 1 2 4 5 8 10
3 1 2

EXERCISE (3)

Problem 3: MMSA of N Numbers

Write a program that reads from the console a sequence of N integer numbers and returns the minimal, the maximal number, the sum and the average of all numbers (displayed with 2 digits after the decimal point).
• The input starts by the number N (alone in a line) followed by N lines, each holding an integer number.
• The output is like in the examples given.

EXERCISE (4)

Problem 3: Examples

Input Output
3 2 5 1 min=1.00 max=5.00 sum=8.00 1 avg=2.67
3 2 -1 4 min=-1.00 max=4.00 sum=5.00 avg=1.67

EXERCISE (5)

Problem 4: Calculate Factorials

Write a program that calculates N! / K! for given N and K. • Challenge: Use only one loop for both factorial calculations

Input Output
8 3 6720

EXERCISE (6)

Problem 5: Matrix of Numbers

Write a program that reads from the console a positive integer number N and prints a matrix like in the examples below. Use two nested loops.
• Challenge: achieve the same effect without nested loops

EXERCISE (7)

Problem 5: Examples

Input Output
2 1 2
2 3
4 1 2 3 4
2 3 4 5
3 4 5 6
4 5 6 7

EXERCISE (8)

Problem 6: Odd and Even Product

You are given N integers (given in a single line, separatedby a space).
• Write a program that checks whether the product of the odd elements is equal to the product of the even elements.
• Elements are counted from 1 to N. so the first element is odd, the second is even, etc.

EXERCISE (9)

Problem 6: Input / Output

Input
• On the first line you will receive the number N
• On the second line you will receive N numbers separated by a whitespace
Output
• If the two products are equal, output a string in the format "yes PRODUCT_VALUE", otherwise write on the console "no ODD PRODUCT_VALUE EVEN_PRODUCT_VALUE"

EXERCISE (10)

Problem 6: Examples

Input Output
5
2 1 1 6 3
yes 6
5
4 3 2 5 2
no 16 15