Bhubaneswar, Odisha, India
+91-8328865778
support@logyscal.com

How For loop works in C# with example code snippet

How For loop works in C# with example code snippet


In C#, a for loop is used to execute a block of code repeatedly based on a condition. It consists of three parts:

  1. Initialization: Initialize the loop control variable.
  2. Condition: Check if the loop control variable meets the condition.
  3. Iteration: Update the loop control variable.

Here’s a simple example of a for loop in C#:

using System;

class Program
{
    static void Main(string[] args)
    {
        // Example: Printing numbers from 1 to 5 using a for loop
        for (int i = 1; i <= 5; i++)
        {
            Console.WriteLine(i);
        }
    }
}

Explanation of the for loop in the example:

  • int i = 1: Initialization – Initialize the loop control variable i to 1.
  • i <= 5: Condition – Check if the loop control variable i is less than or equal to 5.
  • i++: Iteration – Increment the loop control variable i by 1 in each iteration.

The loop will execute as follows:

  • i is initialized to 1.
  • Check if i is less than or equal to 5. Since it’s true, execute the loop body (printing i) and then increment i.
  • Repeat the process until the condition i <= 5 becomes false.

The loop will print numbers from 1 to 5, and then terminate.Hope this helps.

 

Leave a Reply

Your email address will not be published. Required fields are marked *