AlphaCodingSkills

C# - While Loop


Advertisements

Previous Page Next Page

A loop statement allows a program to execute a statement(s) multiple times which provides easier and flexible programming. C# has three loop statements.

  • While loop
  • Do-While loop
  • For loop

The While Loop:

While loop allows a set of statements to be executed repeatedly until a given condition is true. The While loop can be viewed as a repeating if statement.

Syntax


while (condition) {
      statements;
    }

Flow Diagram:

C# While Loop

In below mentioned example, program uses while loop to sum all integers from 1 to 5.

using System;

namespace MyApplication { 
  class MyProgram {
    static void Main(string[] args) {
      int i = 1;
      int sum = 0;
      while (i < 6){
          sum = sum + i;
          i = i+1;
      }
      Console.WriteLine(sum);
    }
  }
}

Output

15

The Do-While Loop:

The Do-While loop in C# is a variant of while loop which execute statements before checking the conditions. Therefore the Do-While loop executes statements at least once.

Syntax


do {
  statements;
}
while (condition);

Flow Diagram:

C# While Loop

The above explained example is programmed using do-while loop and mentioned below:


using System;

namespace MyApplication { 
  class MyProgram {
    static void Main(string[] args) {
      int i = 1;
      int sum = 0;
      do{
        sum = sum + i;
        i = i+1;
      }
      while (i < 6);
      Console.WriteLine(sum); 
    }
  }
}

Output

15

Previous Page Next Page