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

For loop execution model in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A for loop helps you repeat a set of actions many times without writing the same code again and again.

When you want to count from 1 to 10 and do something each time.
When you need to go through each item in a list one by one.
When you want to repeat a task a fixed number of times, like printing a message 5 times.
When you want to process numbers in a range, like checking all numbers from 0 to 100.
When you want to build or fill a collection step by step.
Syntax
C Sharp (C#)
for (initialization; condition; update)
{
    // code to repeat
}

initialization runs once at the start to set up the loop.

condition is checked before each loop; if false, the loop stops.

update runs after each loop to change the loop variable.

Examples
This prints numbers 0 to 4, increasing i by 1 each time.
C Sharp (C#)
for (int i = 0; i < 5; i++)
{
    Console.WriteLine(i);
}
This counts down from 10 to 1, decreasing count by 1 each time.
C Sharp (C#)
for (int count = 10; count > 0; count--)
{
    Console.WriteLine(count);
}
This prints even numbers from 0 to 8 by adding 2 each time.
C Sharp (C#)
for (int i = 0; i < 10; i += 2)
{
    Console.WriteLine(i);
}
Sample Program

This program uses a for loop to print a message 5 times. The loop starts at 1 and goes up to 5.

C Sharp (C#)
using System;

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

The loop variable (like i) is usually declared inside the for statement.

If the condition is false at the start, the loop body will not run at all.

You can use break to stop the loop early if needed.

Summary

A for loop repeats code while a condition is true.

It has three parts: start, check, and change.

Use it to run code a set number of times easily.