Lesson 5.1:

C# while Loop - with programming example


Objective

What is while loop in c#?
while loop structure
Programming example of while loop

What is while loop in c#?

while loop is the one of member of c# loop family. It also requires 3 conditions to execute properly as initialization, condition and increment/decrement. As it is your first chapter of loop statements you will become familiar with it after finishing this chapter.

Structure:

Let's see the structure of while loop as syntax and how to write in a program. It is very easy to write while loop in program.

   int i = 0;
   while (i < 10)
     {
        Console.WriteLine("Hello While Loop");
        i++;
     }
		  

In this previous syntax, we have initialize a variable i=0. Next we have test a condition whether the value of i is less than 10. If condition match the program execute very next line and enter the loop. Here it prints "Hello While Loop" on the console and then increment value of i by 1.

Again the loop control goes to condition and check the value of i whether it is less than 10 or not. If result returns true it does same process until the value of i equal to 10. When condition becomes false the program jump out from the while loop. Let's understand it with graphic.

While Loop

Programming Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace While_Loop
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            while (i < 10)
            {
                Console.WriteLine("Hello While Loop");
                i++;
            }
            Console.ReadKey();
        }
    }
}

		  

Output

Hello While Loop
Hello While Loop
Hello While Loop
Hello While Loop
Hello While Loop
Hello While Loop
Hello While Loop
Hello While Loop
Hello While Loop
Hello While Loop
__

Summary

While loop is one of the most important looping construct in c#. Hope you have learned it and enjoy it. In the next chapter you will learn while true.

BackNext