Looping Statements

Looping in programming means to execute a set of statements or block of code multiple times until a
condition is satisfied.

We have mainly these following lists.

-  While Loop

-  Do While Loop

-  For Loop

-  Nested Loops

While Loop

It checks the condition first and when it is true, it executes the block of code.

Syntax:

While(bool condition)
{
XX statement1;
XX statement2;
}

 

Example 1

 

using System;
namespace SampleProgram {
  class MySample {
    public static void Main(string[] args) {
      int p = 1;
      while (p < 4) {
        Console.WriteLine("P value increment by 1: " + p);
        p++;
      }
    }
  }
}

 

The output will be:

P-value increment by 1: 1
P-value increment by 1: 2
P-value increment by 1: 3

 

Do While Loop:

It is similar to While Loop but it checks the condition after the set of statements are executed at least
once, it executes the set the statements or block of code again until the condition is true.

Syntax:

do
{
XX statement1;
XX statement2;
}
while(bool condition)

 

Example 2

 

using System;
namespace SampleProgram {
  class MySample {
    public static void Main(string[] args) {
      int p = 10;
      do {
        Console.WriteLine("P value increment by 1: " + p);
        p++;
      }
      while ( p < 4 )
    }
  }
}

 

The output will be:

P value increment by 1: 10

 

For Loop:

For Loop is similar to while loop but the condition and number of times the loop to be executed are
defined at For Loop. This Loop declaration makes the code readable and cleaner.

Syntax:

for(variable initialize;condition;increment or decrement)
{
XX statement1;
XX statement2;
}

 

Example 3

 

using System;
namespace SampleProgram {
  class MySample {
    public static void Main(string[] args) {
      for (int k = 1; k < 5; k++) {
        Console.WriteLine("k value increment by 1: " + k);
        p++;
      }
    }
  }
}

 

The output will be

k value increment by 1: 1
k value increment by 1: 2
k value increment by 1: 3
k value increment by 1: 4

 

Nested Loops:

The loops inside the other loops are called Nested loops.

Example 4:

 

using System;
namespace SampleProgram {
  class MySample {
    public static void Main(string[] args) {
      int p = 1;
      while (p < 4) {
        Console.WriteLine("P value increment by 1: " + p);
        while (p < 3) {
          Console.WriteLine("Nested Loop – p value: " + p);
          p++;
        }
        p++;
      }
    }
  }
}

 

The output will be:

P value increment by 1: 1
Nested Loop - p value: 1
Nested Loop - p value: 2
P value increment by 1: 4

 

Related Tutorials