C#/C# Tutorial

C# Iteration Loop - for, foreach, do, while | C# Tutorial for Beginners

DragonTory 2023. 2. 22. 08:25
반응형

C# Iteration Loop - for, foreach, do, while | C# Tutorial for Beginners

 

The iteration statements repeatedly execute a statement or a block of statements.

There are several types of iteration loops you can use to iterate over a collection of elements.

Here are some examples:

 

 1. for loop :

 

The for loop is the most commonly used loop in C#.

It allows you to execute a block of code repeatedly based on a specified condition.

for (int i = 0; i < 10; i++)
{
   // code to be executed
}
In this example, the loop will run 10 times, with i starting at 0 and incrementing by 1 after each iteration.
 
 
 
 2. foreach loop :

 

The foreach loop is used to iterate over a collection of elements, such as an array or a list.

int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int number in numbers)
{
   // code to be executed for each element
}

In this example, the loop will iterate over each element in the numbers array.

 

 3. while loop :

 

The while loop is used to execute a block of code repeatedly as long as a specified condition is true.

int i = 0;
while (i < 10)
{
   // code to be executed
   i++;
}
In this example, the loop will run 10 times, with i starting at 0 and incrementing by 1 after each iteration, until it reaches 10.
 
 
 4. do-while loop:

 

The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at least once, even if the condition is false.

 
int i = 0;
do
{
   // code to be executed
   i++;
} while (i < 10);

In this example, the loop will run 10 times, with i starting at 0 and incrementing by 1 after each iteration, until it reaches 10.

 

 5. break and continue statements:

 

You can use the break and continue statements within a loop to control the flow of execution.

The break statement exits the loop, while the continue statement skips the current iteration and moves on to the next one.

For example, let's say you want to iterate over an array of integers and only print the even numbers:

int[] numbers = { 1, 2, 3, 4, 5 };

foreach (int number in numbers)
{
    if (number % 2 == 1)
    {
        continue; // skip odd numbers
    }
    
    Console.WriteLine(number);
}

In this example, the continue statement skips any odd numbers and only prints the even ones.

 

반응형