C# while Loop

Introduction

The while loop in C# is a control flow statement that allows you to repeatedly execute a block of code as long as a specified condition is true. It is useful when the number of iterations is not known beforehand and you want to keep looping until a certain condition is met.

Syntax

while (condition)
{
    // Code to execute as long as condition is true
}

Components of a while Loop

  1. Condition: This section is evaluated before each iteration of the loop. If the condition is true, the loop body executes. If the condition is false, the loop terminates.
  2. Loop Body: This section contains the code that will be executed on each iteration of the loop.

Example

Here’s a complete example demonstrating the use of the while loop in C#:

using System;

namespace WhileLoopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 1;

            // Using a while loop to print numbers from 1 to 10
            while (counter <= 10)
            {
                Console.WriteLine("Number: " + counter);
                counter++; // Increment the counter
            }

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Number: 6
Number: 7
Number: 8
Number: 9
Number: 10
Program finished.

Explanation

  1. Initialization: int counter = 1; initializes the counter variable to 1.
  2. Condition: counter <= 10; checks if the counter is less than or equal to 10. If true, the loop body executes.
  3. Loop Body: Console.WriteLine("Number: " + counter); prints the current value of the counter. counter++; increments the counter by 1.

Example: Summing Numbers with a while Loop

This example calculates the sum of numbers from 1 to 100 using a while loop:

using System;

namespace SumWhileLoopExample
{
    class Program
    {
        static void Main(string[] args)
        {
            int sum = 0;
            int number = 1;

            // Using a while loop to calculate the sum of numbers from 1 to 100
            while (number <= 100)
            {
                sum += number;
                number++;
            }

            Console.WriteLine("Sum of numbers from 1 to 100: " + sum);

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Sum of numbers from 1 to 100: 5050
Program finished.

Explanation

  1. Initialization: int sum = 0; int number = 1; initializes the sum and number variables.
  2. Condition: number <= 100; checks if the number is less than or equal to 100. If true, the loop body executes.
  3. Loop Body: sum += number; adds the current value of the number to the sum. number++; increments the number by 1.

Example: Reading User Input

This example uses a while loop to read user input until the user enters "exit":

using System;

namespace ReadInputWhileLoop
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "";

            // Using a while loop to read user input until "exit" is entered
            while (input.ToLower() != "exit")
            {
                Console.WriteLine("Enter a command (type 'exit' to quit):");
                input = Console.ReadLine();
                Console.WriteLine("You entered: " + input);
            }

            // This will always be executed
            Console.WriteLine("Program finished.");
        }
    }
}

Output

Enter a command (type 'exit' to quit):
hello
You entered: hello
Enter a command (type 'exit' to quit):
exit
You entered: exit
Program finished.

Explanation

  1. Initialization: string input = ""; initializes the input variable to an empty string.
  2. Condition: input.ToLower() != "exit"; checks if the input is not equal to "exit". If true, the loop body executes.
  3. Loop Body: Console.WriteLine("Enter a command (type 'exit' to quit):"); prompts the user for input. input = Console.ReadLine(); reads the user input. Console.WriteLine("You entered: " + input); prints the entered input.

Conclusion

The while loop is a versatile control flow statement that allows you to repeat a block of code as long as a specified condition is true. It is useful when the number of iterations is not known beforehand. By understanding and using the while loop, you can handle various repetitive tasks in your C# programs efficiently.

Leave a Comment

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

Scroll to Top