C# While

Learn 'while' loop in C#.

While Loop

A "while" loop is used to repeatedly execute a block of code as long as a specified condition is 'true'. The basic syntax of a while loop is as follows:

while (condition)
{
    // Code to be executed as long as the condition is true
}

Here's a simple example that demonstrates the use of a 'while' loop to print numbers from 1 to 5:

cs Copy Code
using System;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5 };

        foreach (var number in numbers)
        {
            Console.WriteLine(number);
        }

    }
}

The 'while' loop continues to execute the block of code as long as the condition 'i <= 5' is true. Inside the loop, 'Console.WriteLine(i)' prints the current value of 'i', and 'i++' increments the value of 'i' by 1 in each iteration.

Output:
1
2
3
4
5

Note: It's crucial to ensure that the condition eventually becomes false to prevent an infinite loop. In the example above, the loop will terminate when 'i' becomes greater than 5.

while (1) {...}

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.