Lesson 5.2:

C# while(true) Loop - with programming example


Objective

What is while(true) loop in c#?
while(true) loop structure
Programming example

What is while(true) loop in c#?

A while(true) loop is another kind of looping statement in c# which is terminated by break clause inside loop. You may also call it as infinite loop which stops its execution when break clause called.

Structure:

  while(true)
  {
    if(condition)
    break;
  }
		  

How it works:

This loop initiate an infinite loop and in each execution it process an if statement to evaluate condition. When condition becomes true a break clause called and it stop execution of while(true) loop.

While(true) Loop

Programming Example

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

namespace while_true
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            while (true)
            {
                Console.WriteLine("Hello While True");
                if (i == 10)
                {
                    Console.WriteLine("Breaking Loop");
                    break;
                }
                i++;
            }
            Console.ReadKey();
        }
    }
}

		  

Output

Hello While True
Hello While True
Hello While True
Hello While True
Hello While True
Hello While True
Hello While True
Hello While True
Hello While True
Hello While True
Hello While True
Breaking Loop

__

Explanation:

In the previous programming example, we have initialized i variable by 0. Next initiate a while(true) loop that prints "Hello While True" on the console and then compare i == 10. If condition not matched it increment value of i by 1 and again does same process until the value of i becomes 10. When i==10 then it prints "Breaking Loop" on console and exit from loop using break clause.

Summary

In this chapter you have learned about while true loop. In the next chapter you will learn about do while loop.

BackNext