Introduction
Loops help us repeat tasks easily without writing the same code many times. They save time and make programs shorter and clearer.
Loops help us repeat tasks easily without writing the same code many times. They save time and make programs shorter and clearer.
for (int i = 0; i < count; i++) { // code to repeat } while (condition) { // code to repeat } do { // code to repeat } while (condition);
for loop is used when you know how many times to repeat.
while and do-while loops repeat based on a condition.
for (int i = 1; i <= 5; i++) { Console.WriteLine(i); }
int count = 3; while (count > 0) { Console.WriteLine("Counting down: " + count); count--; }
int number = 0; do { Console.WriteLine("Number is " + number); number++; } while (number < 3);
This program uses a for loop to print numbers from 1 to 5, showing how loops repeat code easily.
using System; class Program { static void Main() { Console.WriteLine("Counting from 1 to 5:"); for (int i = 1; i <= 5; i++) { Console.WriteLine(i); } } }
Loops help avoid repeating code manually, making programs easier to read and maintain.
Be careful to set conditions correctly to avoid infinite loops that never stop.
Loops repeat code to save time and effort.
Use loops when you want to do something many times.
Common loops in C# are for, while, and do-while.
for loop in C#?int sum = 0;
for (int i = 1; i <= 3; i++)
{
sum += i;
}
Console.WriteLine(sum);int i = 0;
while (i < 3)
{
Console.WriteLine(i);
}Pass the test and this pattern moves unknown