By   Calendar icon Mar 25, 2019   Level 1 icon

Description:

Here we explain what a while loop is in C# and we give some examples. We are also interested in nested loops.

Preferencesoft

While loop

A while loop is an instruction to repeat a statement or sequence of statements as long as a Boolean condition remains true.

The while statement has the following syntax:

while (condition) instruction;

or

while (condition)
{
   instruction_1;
   // ...
   instruction_n;
}

The condition can be any expression that evaluates to a Boolean.

When the condition becomes false, it stops repeating the instructions.

Difference with for loop

The for statement has almost the same flow chart as while, but the for statement allows to manage counters while while is a very basic repetition statement.

Examples

Example

Write a program that asks the user for an integer n, until condition n?10 is satisfied. Whenever n<10 we will display "the integer is not suitable, please try again".

using System;
namespace whileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        int n=0;
        while (n<10)
        {
            System.Console.Write("Enter an integer n>=10 ");
            n=int.Parse(Console.ReadLine());
            if (n<10)
                System.Console.WriteLine("The integer is not suitable, please try again");
        }
        System.Console.WriteLine("n={0}",n);
        System.Console.ReadKey();
    }
}
}

Example

Write a program that asks repeatedly the user for a list of real numbers, checks if each number is appropriate and stops typing when the user presses the enter key without any data.

using System;
using System.Collections.Generic;
namespace whileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        List<double> dL = new List<double>();
        bool notEnd = true;
        while (notEnd)
        {
            string s = System.Console.ReadLine();
            double d = 0.0;
            bool isOK = double.TryParse(s, out d);
            if (isOK) dL.Add(d);
            else if (string.IsNullOrEmpty(s)) notEnd = false;
            else System.Console.WriteLine("{0} is not a real number",s);
        }
        System.Console.WriteLine("length={0}",dL.Count);
        System.Console.ReadKey();
    }
}
}

Example

Write a program that asks the user for an integer n until it is greater than 50.

using System;
namespace whileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        int n=0;
        while (n<=50)
        {
            System.Console.Write("Enter an integer >50 ");
            n=int.Parse(Console.ReadLine());
            if (n<=50)
                System.Console.WriteLine("must be greater than 50");
        }
        System.Console.Write("n={0}",n);
        System.Console.ReadKey();
    }
}
}

Example

Write a program that asks for an integer n?0 and that displays all integers from n to n^2-ln(n + 1).

using System;
namespace whileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        System.Console.Write("Enter an integer n>=0 ");
        int n=int.Parse(Console.ReadLine());
        if (n>=0)
        {
            int k=n;
            while (k<=n*n-Math.Log(n + 1))
                System.Console.WriteLine("{0}",k++);
        }
        else System.Console.WriteLine("must be >=0");
        System.Console.ReadKey();
    }
}
}

Example

Write a program that repeatedly asks for a real double x to the user then displays x^5 + [x] -1 (where [x] is floor(x)) and asks the user:

Do you want to start again [o/n]?

and that stops if the user responds n.

using System;
using static System.Math;

namespace whileloop
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        bool notEnd = true;
        while (notEnd)
        {
            System.Console.WriteLine("Enter a real number ");
            double x=double.Parse(Console.ReadLine());
            System.Console.WriteLine("Result: {0}", x*x*x*x*x+Math.Floor(x)-1);
            System.Console.Write("Do you want to start again [o/n]?");
            string ans=System.Console.ReadLine();
            notEnd = (ans != "n");
        }
    }
}
}

Nested while loop

A loop is nested in another if it is part of the instructions of the other.

For example:

while (condition1)   
   while (condition2)

Example

Write a program that asks for an integer n?1 for each integer whose square is less than or equal to n, displays in column all its divisors.

using System;
namespace divisors
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("Enter an integer n >= 1");
        int n = int.Parse(Console.ReadLine());
        if (n >= 1)
        {
            int k = 0;
            while (k * k <= n)
            {
                Console.WriteLine("Divisors of {0}", k);
                int i = 1;
                while (i <= k)
                {
                    if (k % i == 0)
                        Console.Write("{0}  ", i);
                    ++i;
                }
                Console.WriteLine();
                k++;
            }
        }
        System.Console.ReadKey();
    }
}
}

Example

Write a program that requests an integer n?1 to the user and displays the following figure:

For n = 4

*******
 *****
  ***
   *
  ***
 *****
*******

with 2n-1 lines

using System;
namespace divisors
{
class Program
{
    [STAThread]
    static void Main(string[] args)
    {
        Console.WriteLine("Enter an integer n >= 0");
        int n = int.Parse(Console.ReadLine());
        int len = 2*n-1;
        int row = 0;
        while (row < n)
        {
            int i = 0;
            while (i < row)
            {
                Console.Write(" ");
                i++;
            }
            i=0;
            while (i < len - 2*row)
            {
                Console.Write("*");
                i++;
            }
            Console.WriteLine();
            ++row;
        }
        row -= 2;
        while (row >= 0)
        {
            int i = 0;
            while (i < row)
            {
                Console.Write(" ");
                i++;
            }
            i=0;
            while (i < len - 2*row)
            {
                Console.Write("*");
                i++;
            }
            Console.WriteLine();
            --row;
        }
        System.Console.ReadKey();
    }
}
}

Empty statement

It is possible with while not to set an instruction after the condition:

while (condition);

We consider in this case that we execute the empty instruction (between the closing parenthesis and the semi-colon)

But we must be sure that the condition that will be a function ends up becoming false in order to avoid an infinite loop.

Infinite loop

A while loop is infinite when the condition will always be true and that there is not in the loop body, instruction forcing an exit of the loop like break, return or throw.

for example

while (true) 
   Console.WriteLine("Hello");

However, such a loop is to be avoided since if the program is not being debugged, it will be impossible to stop it, but it will be stopped by the operating system.


CSharp

Categories