Looping – While loop

October20, 2017
by admin

Syntax:

while(<conditional expression>)
{
  // statement or statements 
  // to be executed
}

Lets have a look at the above syntax of the ‘while’ loop. It is simple and straight forward.

The ‘while’ loop starts with ‘while’ keyword.

After ‘while’ keyword, there is an opening and closing parenthesis containing conditional expression. Note that this conditional expression is a must to have argument.

The ‘while’ loop has a body enclosed within the opening and closing curly braces where you can put your statements that you want to be repeatedly executed.

While loop repeatedly executes till the conditional expression returns true. As soon as it returns false, while loop terminates.

Lets understand ‘while’ loop with a simple example.

Ex:

Problem:

Write a program to display numbers from 1 to 10 in sequential order to console output each on separate lines.

Solution:


  using System;

  namespace LoopingDemo
  {
    public class WhileDemo()
    {
      // counter variable declaration and initialization
      int counter = 1;

      while(counter <= 10)   // while statement
      {
        // statements to be repeatedly executed
        Console.WriteLine(counter);

        // increment/decrement counter variable
        counter++;
      }
    
      Console.WriteLine("Enter any key to exit: ");
      Console.ReadLine();
    }
  }

Output:

1

2

3

4

5

6

7

8

9

10

In above code example, we need to write a program to print the numbers from 1 to 10 to the console output. Instead of writing code statements for each number we have used while loop statement in C# code.

On the first line of code, we have declared a loop counter variable and named it as 'counter'. You can set any name for this variable. We have named it 'counter' to understand quickly its role in a loop. While declaring the counter with an integer data type, we also initialized it with value 1 since we need to print values from 1 to 10.

int counter = 1;

After declaring and initializing loop counter variable, on the next line we have written while statement with the following conditional expression so that our while loop will execute repeatedly till the value of 'counter' is less than or equal to 10.

while(counter <= 10) 

In the body of 'while' loop, we have written statements to be repeatedly executed. We wrote a single statement that prints the current value of the 'counter' variable to console output using the 'WriteLine()' method of 'Console' static class.

Console.WriteLine(counter);

After writing the body statements that need to be executed repeatedly, before closing the body of while loop with closing curly brace, we have written a statement to increment the value of 'counter' variable.

counter++;

Please note that incrementing or decrementing the value of the 'counter' variable in the body of while loop (as well as do while loop which we will discuss next) is extremely important since we need to execute the while loop till conditional expression returns true. If you forgot to write this statement, then the 'counter' variable value will never change. In this code example, it will remain 1 forever and it will never change to more than 10 and our while loop conditional expression will never return false which will cause to infinite loop. This is the thing you must make sure to avoid infinite loop.

Every time loop executes, counter variable value will increase by 1. That means for the first entry or iteration, its value is 1 so it prints the value 1 to console output and then increase the value by 1 and change it to 2.

For the second iteration, loop print the current value of the 'counter' variable that is 2 to console output and then again increases the value of the 'counter' variable by 1 and change it to 3.

This flow executes repeatedly till the value of 'counter' variable is less than or equal to 10. When the value of the counter variable becomes 10, loop statements print the current value of 'counter' variable that is 10 to the console output and then increases its value by 1 and change it to 11.

When control flow executes the while loop for the 11th time, the current value of the counter variable is 11. Since the value is 11 which is more than comparable value in our conditional expression that is 10, conditional expression returns false and while loop terminate and control flow goes to the very next statement after closing parenthesis of 'while' loop body.

After executing the 'while' loop and displaying output to the user, we simply asked the user to enter any key to stop the application with the following code.

Console.WriteLine("Enter any key to exit: ");
Console.ReadLine();

When you compile and run the application, you will see the result as shown in the output section.


While writing code for while loop in C#, you need to do following four things.

1. Declare and initialize a counter variable before starting the 'while' loop.

2. The 'while' loop conditional expression.

3. The statement or statements to be repeatedly executed.

4. Increment/decrement loop counter variable.

C# Fundamentals