0
0
C Sharp (C#)programming~5 mins

Why loops are needed in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Loops help us repeat tasks easily without writing the same code many times. They save time and make programs shorter and clearer.

When you want to print numbers from 1 to 10.
When you need to check every item in a list or array.
When you want to keep asking a user for input until they give a valid answer.
When you want to repeat a task multiple times, like drawing shapes or calculating sums.
When you want to process data until a certain condition is met.
Syntax
C Sharp (C#)
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.

Examples
This prints numbers 1 to 5 using a for loop.
C Sharp (C#)
for (int i = 1; i <= 5; i++) {
    Console.WriteLine(i);
}
This counts down from 3 to 1 using a while loop.
C Sharp (C#)
int count = 3;
while (count > 0) {
    Console.WriteLine("Counting down: " + count);
    count--;
}
This prints numbers 0 to 2 using a do-while loop.
C Sharp (C#)
int number = 0;
do {
    Console.WriteLine("Number is " + number);
    number++;
} while (number < 3);
Sample Program

This program uses a for loop to print numbers from 1 to 5, showing how loops repeat code easily.

C Sharp (C#)
using System;

class Program {
    static void Main() {
        Console.WriteLine("Counting from 1 to 5:");
        for (int i = 1; i <= 5; i++) {
            Console.WriteLine(i);
        }
    }
}
OutputSuccess
Important Notes

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.

Summary

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.