C# While Loop

In the C# programming language, loops play a crucial role in repeating a set of statements until a particular condition is satisfied. The while loop stands out for its straightforwardness and flexibility.

In C#, the while loop is employed to run a block of code iteratively as long as the specified condition holds true. This loop is particularly handy when the exact number of iterations is uncertain.

Syntax

It has the following syntax.

Example

while(condition)

{

// code to be executed

}

In this syntax,

  • Condition: It is used to check the given condition of the program. If the condition of the program is matched, it executes the block of code. If the condition of the program is not matched, it exits the loops.
  • Update Expression: It is used to update the loop variable value, whether it increments or decrements.
  • Body: It represents the main block of the loop where we write the block of code.
  • Flow Diagram of While Loop

  • First, we have to initialize the value.
  • Next, we go to the while loop.
  • After that, we check the given condition of the program. If the condition of the program becomes true, execute the block of code. If the condition of the program becomes false, it exits the loop.
  • End of the program.
  • If the condition of the program becomes true, execute the block of code.
  • If the condition of the program becomes false, it exits the loop.
  • C# While Loop Example

Let's consider an example to illustrate a while loop that outputs numbers from 1 to 10.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int i = 1;   //initialization 

        while (i <= 10)  //condition

        {

            Console.WriteLine(i);

            i++;   // updation

        }

    }

}

Output:

Output

1

2

3

4

5

6

7

8

9

10

Explanation:

In this illustration, we display a sequence of numbers from 1 to 10 by employing a while loop. Initially, we set the integer variable i to 1. Subsequently, the program evaluates the condition (i<10). When this condition is met, the program outputs the current value of i. If the condition is not satisfied, the loop terminates. Ultimately, the result is shown using the Console.WriteLine method.

Factorial Number Program Using While Loop

Here is a demonstration of calculating factorial using the while loop in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int num, fact = 1;

        Console.WriteLine("Enter the number:");

        num = int.Parse(Console.ReadLine());

        int i = 1; // initializing the value

        while (i <= num)  // condition of value

        {

            fact *= i;

            i++;        // updation of value

        }

    Console.WriteLine($"The factorial of {num} is {fact}");

    }

}

Output:

Output

Enter the number:

5

The factorial of 5 is 120

Explanation:

In this illustration, the factorial of a number is computed through the implementation of while loop statements. Two variables, num and fact, are declared to store an integer value. The user is then asked to input the number for which the factorial needs to be calculated. Subsequently, a while loop is utilized to calculate the factorial, and the result is displayed using the Console.WriteLine method.

Nested While Loop

In C#, a nested while loop is a form of while loop statement, in which a while loop is enclosed within another while loop. Within a nested loop, the inner loop runs in its entirety for every iteration of the outer loop.

Syntax

It has the following syntax.

Example

while(condition)

{

while(condition)

{

// statements

}

// statements

}

Print Pyramid by Using Nested While Loop in C#.

Let's consider a basic illustration demonstrating how to display a triangle using the while loop in C#.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int r = 1;

        while (r <= 5)  // outer loop of the program

        {

            int c = 1;

            while (c <= r)  // inner loop of the program 

            {

                Console.Write("* ");

                c++;

            }

            Console.WriteLine();

            r++;

        }

    }

}

Output:

Output

* 

* * 

* * * 

* * * * 

* * * * *

Explanation:

In this instance, we have employed the integer data type r and c. Here, r signifies the external loop of the code, and c signifies the internal loop of the code. As the external loop executes once, the internal loop completes its entire iteration. Ultimately, we utilized the Console.WriteLine method to display the result.

Print Multiplication Table Using Nested While Loop

Let's consider an example where we demonstrate how to display a table by employing nested while loop structures.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int row = 2;

        while (row < 4) // Outer loop 

        {

            int col = 1;

            while (col <= 10) // Inner loop 

            {

                Console.WriteLine($"{row} x {col} = {row * col}");

                col++;

            }

            Console.WriteLine(); // breaking the line

            row++;

        }

    }

}

Output:

Output

2 x 1 = 2

2 x 2 = 4

2 x 3 = 6

2 x 4 = 8

2 x 5 = 10

2 x 6 = 12

2 x 7 = 14

2 x 8 = 16

2 x 9 = 18

2 x 10 = 20

3 x 1 = 3

3 x 2 = 6

3 x 3 = 9

3 x 4 = 12

3 x 5 = 15

3 x 6 = 18

3 x 7 = 21

3 x 8 = 24

3 x 9 = 27

3 x 10 = 30

Explanation:

In this instance, we've defined integer variables named row and col. Subsequently, we've initialized row to 2 and col to 1. The variable row is responsible for controlling the outer loop of the program, while col manages the inner loop, which handles the multiplication logic. As the outer loop executes, the inner loop completes all its iterations. Ultimately, we utilize the Console.WriteLine method to display the resulting output.

C# Infinitive while Loop

In C#, an infinite loop is a loop that continues endlessly without ever stopping. Put simply, an infinite loop is a loop where the condition always evaluates to true.

Syntax:

It has the following syntax.

Example

While(true)

{

// block of the code

}

Simple Example of Infinite While Loop:

Let's consider a basic example of an endless while loop.

Example

Example

using System;

class Program

{

    static void Main()

    {

        while (true)

        {

            Console.WriteLine("Infinitive While Loop");

        }

    }

}

Output:

Output

Infinitive While Loop

Infinitive While Loop

Explanation:

In this illustration, we've established an endless while loop by setting a condition that always evaluates to true. Next, we've utilized the Console.WriteLine method to showcase the result.

Controlling While Loop Statement

In C#, there exist two variations of controlling while loop statements:

  • Employing the break statement
  • Implementing the Continue Statement
  • Using break statement

In C#, the break statement is employed to terminate the execution of the while loop's condition.

Syntax:

It has the following syntax.

Example

break;

C# Example Break Statement using While Loop

Let's consider a basic scenario where the break statement is employed to halt the execution.

Example

Example

using System;	

public class Program

{

    public static void Main(string[] args)

    {

        int s = 1;

        while (s < 10)

        {

            if (s == 6)

            {

                break;  // exit the code when s equal to 5.

            }

            Console.WriteLine(s);

            s++;

        }

        Console.WriteLine("Exit the loop = " + s);

    }

}

Output:

Output

1

2

3

4

5

Exit the loop = 6

Explanation:

In this instance, we display the integers from 1 to 5. Utilizing the integer data type, we assign the variable s a value of 1. Subsequently, we evaluate the specified condition. Should the value of s equal 6, the program terminates using the break keyword. Lastly, we employ the Console.WriteLine method to display the result.

Using Continue Statement:

In C#, the continue statement is employed to bypass the current iteration and proceed to the following iteration.

Syntax:

It has the following syntax.

Example

while (condition)

{

    if (condition)

    {

        continue; // skips to the next iteration

    }

    // More code // continue execute the code

}

C# Example of Switch Statement using While Loop

Let's consider a basic example that utilizes the continue statement to bypass certain iterations during execution.

Example

Example

using System;

class Program

{

    static void Main()

    {

        int s = 0;  // initializing the value

        while (s < 10)  // condition of value

        {

            s++; // increment of value

            if (s == 6)

            {

                continue; // skip the 6 number

            }

            Console.WriteLine(s); // print the number

        }

    }

}

Output:

Output

1

2

3

4

5

7

8

9

10

Explanation:

In this instance, the continue statement is employed to bypass certain parts of the code execution. An integer variable, s, is declared and initialized with a value of 0. Subsequently, a condition (s<10) is evaluated. The following code block is executed only if the condition holds true. Upon meeting the condition, the continue keyword is utilized to skip a specific iteration, and the output is displayed using the Console.WriteLine method.

Conclusion

In C#, the while loop construct enables us to address a crucial challenge in programming. It is vital for executing repetitive tasks within programs and proves advantageous for conducting dynamic computations.

C# While Loop FAQs

The four primary elements of the While Loop are the condition, initialization, body, and iteration.

The primary elements of the while loop consist of Initialization, Condition, main body, and Incrementation. Initially, we set the value. Subsequently, we evaluate the conditions, execute the main body code if the condition is met, and then increment the value.

The break keyword in a while loop is utilized to immediately terminate the loop's execution.

In C#, the break keyword is employed to terminate the loop during program execution.

3) What is the main purpose of a while loop?

The primary function of a while loop is to repeatedly execute a section of the program. It is highly advantageous for developers when computing dynamic code.

4) What is an actual scenario where a while loop is commonly applied in practice?

The act of withdrawing money from an ATM serves as a practical demonstration of a while loop in action. Upon inputting their PIN, the user's provided code is verified against the correct PIN. Access to cash for withdrawal is granted only if the PIN provided matches the correct one; otherwise, the user is denied the ability to withdraw funds.

5) What is an Infinite While loop?

An infinite loop is a loop that runs continuously without stopping or exiting the program. This situation happens when the loop condition remains perpetually true.

Input Required

This code uses input(). Please provide values below: