C# - For Loop



The C# for loop is a repetition control structure that executes a block of code a specific number of times instead of writing the same code multiple times. It is especially useful when the number of iterations is known in advance.

Syntax of for Loop

Following is the syntax of the C# for loop in C# is −

for ( init; condition; increment ) {
   statement(s);
}

Control Flow of a for Loop

Following is the control flow of the for loop −

  • The init step is executed first, and only once. This step allows you to declare and initialize any loop control variables. You are not required to put a statement here, as long as a semicolon appears.

  • Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false, the body of the loop does not execute and flow of control jumps to the next statement just after the for loop.

  • After the body of the for loop executes, the flow of control jumps back up to the increment statement. This statement allows you to update any loop control variables. This statement can be left blank, as long as a semicolon appears after the condition.

  • The condition is now evaluated again. If it is true, the loop executes and the process repeats itself (body of loop, then increment step, and then again testing for a condition). After the condition becomes false, the for loop terminates.

Flow Diagram

for loop in C#

Example of for Loop

Following is the basic example of the for loop in the cSharp program

using System;
namespace Loops {
   class Program {
      static void Main(string[] args) {
         
         /* for loop execution */
         for (int a = 10; a < 20; a = a + 1) {
            Console.WriteLine("value of a: {0}", a);
         }
         Console.ReadLine();
      }
   }
} 

When the above code is compiled and executed, it produces the following result −

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

Another Example

Here, in this example, we use the for loop to display the even number −

using System;
namespace Loops {
   class Program {
      static void Main(string[] args) {
         
         /* for loop execution */
         for (int a = 10; a < 20; a = a + 1) {
            if(a%2==0)
               Console.WriteLine("Even Value: {0}", a);
         }
         Console.ReadLine();
      }
   }
}

Following is the output of the code −

Even Value: 10
Even Value: 12
Even Value: 14
Even Value: 16
Even Value: 18

Nested for Loop

In C#, the for loop can be nested. The nested for loop refers to using one for loop inside another.

Syntax

The syntax of a nested for loop in C# is as follows:

for (initialization; condition; increment)
{
    for (initialization; condition; increment)
    {
        // Inner loop body
    }
    // Outer loop body
}

Example

In the following example, we are using nested for loops to generate and display a multiplication table for numbers ranging from 1 to 5:

using System;

class Program
{
    static void Main()
    {
        for (int i = 1; i <= 5; i++)
        {
            for (int j = 1; j <= 5; j++)
            {
                Console.Write(i * j + "\t");
            }
            Console.WriteLine();
        }
    }
}

Following is the output of the code −

1	2	3	4   5	
2	4	6	8	10	
3	6	9	12	15	
4	8	12	16	20	
5	10	15	20	25	

Use Cases of a C# For Loop

1. Iterating Over Arrays and Lists

The for loop can be used to iterate over elements in an array or list.

int[] numbers = { 1, 2, 3, 4, 5 };
for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

2. Printing Patterns

The for loop can also be used to print different type of patterns or to print the data in different patterns.

int n = 5;
for (int i = 1; i <= n; i++)
{
    for (int j = 1; j <= i; j++)
    {
        Console.Write("* ");
    }
    Console.WriteLine();
}

The above code snippets print the pattern of asterisks.

3. Implementing Counters

The for loop can be used for counting occurrences in data processing.

string str = "hello world";
char target = 'o';
int count = 0;

for (int i = 0; i < str.Length; i++)
{
    if (str[i] == target)
        count++;
}

Console.WriteLine($"Character '{target}' appears {count} times.");

4. Searching in an Array

The for loop can be used to search an element from an array.

int[] arr = { 10, 20, 30, 40, 50 };
int target = 30;
bool found = false;

for (int i = 0; i < arr.Length; i++)
{
    if (arr[i] == target)
    {
        found = true;
        Console.WriteLine($"Element {target} found at index {i}");
        break;
    }
}

if (!found)
    Console.WriteLine("Element not found.");

5. Generating Fibonacci Series

If you want to generate a Fibonacci series, the for loop is used.

int a = 0, b = 1, c, n = 10;
Console.Write($"{a} {b} ");

for (int i = 2; i < n; i++)
{
    c = a + b;
    Console.Write(c + " ");
    a = b;
    b = c;
}
Advertisements