Topics covered:

  • What is a Loop?
  • Loops in C#
    • while loops
    • dowhile loops
    • for loops
    • foreach loops
  • Special loop operators
    • break , continue , goto
  • Nested loops

Video (in Bulgarian)

Presentation Content

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

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

Using Do-While Loop

  • Another loop structure is:
  • The block of statements is repeated
    • While the boolean loop condition holds
  • The loop is executed at least once

For Loops

  • The typical for loop syntax is:
  • Consists of
    • Initialization statement
    • Boolean test expression
    • Update statement
    • Loop body block

The Initialization Expression

  • 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

  • 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

For Loops

  • The typical foreach loop syntax is:
  • 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

What Is Nested Loop?

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

C# Jump Statements

  • Jump statements are:
    • break , continue , goto
  • How continue works?
    • 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)

Summary

  • C# supports four types of loops:
    • while
    • do-while
    • for loops
    • foreach loops
  • Nested loops can be used to implement more complex logic
  • The operators continue , break & goto can control the loop execution