LOOPS

LOOPS
  1. While Loop:

The while loop executes a block of code as long as a certain condition is true. The syntax of the while loop is as follows:

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

				
			

Example:

				
					int i = 1;

while (i <= 5)
{
    Console.WriteLine(i);
    i++;
}


				
			
  1. Do-While Loop:

The do-while loop is similar to the while loop, but it executes the block of code at least once before checking the condition. The syntax of the do-while loop is as follows:

				
					do
{
    // Code to execute at least once
} while (condition);


				
			

Example:

				
					int i = 1;

do
{
    Console.WriteLine(i);
    i++;
} while (i <= 5);

				
			
  1. For Loop:

The for loop executes a block of code a specified number of times. The syntax of the for loop is as follows:

				
					for (initialization; condition; increment)
{
    // Code to execute while the condition is true
}

				
			

Example:

				
					for (int i = 1; i <= 5; i++)
{
    Console.WriteLine(i);
}

				
			
  1. Foreach Loop:

The foreach loop is used to iterate over elements of an array or collection. The syntax of the foreach loop is as follows:

				
					foreach (type element in collection)
{
    // Code to execute for each element
}

				
			

Example:

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

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

				
			
Join To Get Our Newsletter
Spread the love