Loops
What is Loops
Types of Loops in C#
Loops are mainly divided into following types:
-
For Loop
For Loop in C# is a control flow statement that allows us to repeatedly execute a block of code a specified number of times. The For Loop in C# is used when we know the exact number iterations. It contain three stages i.e. initialization, condition and increment or decrement operation.
syntax
Static Code Layout Referencefor (initialization; condition; iterator)
{
// Code to be executed
}
-
Initialization: Runs only once when the loop begins. This is typically where you declare and set your loop counter variable.
-
Condition: A Boolean expression evaluated before every iteration. If true, the loop body runs; if false, the loop terminates.
-
Iterator: Executes at the end of every loop iteration, usually incrementing or decrementing the counter variable.
syntax
Code Examples-
Basic Incrementing Loop (Counting Up)
Write a program to print 1 to 10 numbers
Static Code Layout Referencefor (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// Output: 0, 1, 2, 3, 4
-
Decrementing Loop (Counting Down)
Write a program to print 1 to 10 numbers
Static Code Layout Referencefor (int i = 0; i < 5; i++)
{
Console.WriteLine(i);
}
// Output: 0, 1, 2, 3, 4
-
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
}
}