C# While Loop

To  expert programmer from novice, you need to complete knowledge the looping segments. Loop is very important thing in every programming language that saves you from repetitive nature of work. The C# supports  three loops,While, do while, and for loop. However, you can also use foreach and goto statement for looping statements.

While loop is one of the most important looping construct, that is being widely used in C sharp programming language.

Each time the while loop executed, it checks for condition whether the value of i is less than 10 or not. If the value of i is less than 10, the loop will be executed and increment i by one and then print the value of i. When the value of i reaches 10, the while(i<10) condition becomes false and terminates the loop. To understand more clearly while loop, study the following example that print table of given number using while loop.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace While_Loop_Example
{
    class Program
    {
        static void Main(string[] args)
        {
            int n1, res, i;
 
            Console.WriteLine("Enter Any  number");
            n1 = Convert.ToInt32(Console.ReadLine());
 
            i = 1; //Initialization
            //Check whether condition matches or not
            while (i <= 10)
            {
                res = n1 * i;
                Console.WriteLine("{0} x {1} = {2}", n1, i, res);
                i++; //Increment by one
            }
            Console.ReadLine();
        }
    }
}

Sometime, you don’t know about the starting loop position but want to execute some code in while loop. Or, you might want to run infinite loop that will be terminate with special character. In this situation, you can use while(true) as infinite loop.

Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace While_Loop_With_True
{
    class Program
    {
        static void Main(string[] args)
        {
            int num, sum = 0, res = 0;
            Console.WriteLine("Enter number to add. Press x for Terminate the program");
            while (true)
            {
                num = Convert.ToInt32(Console.ReadLine());
                if (num == -1)
                {
                    break;
                }
                sum = res;
                res += num;
                Console.WriteLine("\n{0} + {1} = {2}", sum, num, res);
            }
            Console.WriteLine("\n\nAborting... Press Enter.");
            Console.ReadLine();
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *