Sunday, 21 July 2024

for loop in C#

 ## C# `for` Loop: Explanation, Theory, and Examples


### Explanation


A `for` loop in C# is a control flow statement that allows code to be executed repeatedly based on a boolean condition. It is typically used when the number of iterations is known before entering the loop.


### Theory


The `for` loop in C# consists of three main parts:

1. **Initialization**: This step is executed once before the loop starts. It typically initializes one or more loop control variables.

2. **Condition**: This boolean expression is evaluated before each iteration of the loop. If the condition is true, the loop body is executed; if false, the loop terminates.

3. **Iteration**: This step is executed after each iteration of the loop body. It typically updates the loop control variables.


The basic syntax of a `for` loop in C# is:


```csharp

for (initialization; condition; iteration)

{

    // Code to be executed

}

```


### Diagram


Here is a flowchart representing the C# `for` loop:


```

            +--------------------+

            |   Initialization   |

            +--------------------+

                     |

                     v

            +--------------------+

            |     Condition      |

            +--------------------+

                     |

       +-------------+------------+

       |             |            |

       | true        | false      |

       |             v            |

       |     +----------------+   |

       |     |  Execute Code  |   |

       |     +----------------+   |

       |             |            |

       |             v            |

       |     +----------------+   |

       +----->  Iteration     +---+

             +----------------+

```


### Examples


#### Example 1: Printing Numbers from 1 to 5


Here is an example of a `for` loop in C# that prints numbers from 1 to 5:


```csharp

using System;


class Program

{

    static void Main()

    {

        for (int i = 1; i <= 5; i++)

        {

            Console.WriteLine(i);

        }

    }

}

```


**Explanation**:

- **Initialization**: `int i = 1;` initializes the loop control variable `i` to 1.

- **Condition**: `i <= 5;` continues the loop as long as `i` is less than or equal to 5.

- **Iteration**: `i++` increments `i` by 1 after each iteration.


**Output**:

```

1

2

3

4

5

```


#### Example 2: Iterating Over an Array


Here is an example of a `for` loop in C# that iterates over an array of fruits and prints each one:


```csharp

using System;


class Program

{

    static void Main()

    {

        string[] fruits = { "apple", "banana", "cherry" };

        for (int i = 0; i < fruits.Length; i++)

        {

            Console.WriteLine(fruits[i]);

        }

    }

}

```


**Explanation**:

- **Initialization**: `int i = 0;` initializes the loop control variable `i` to 0.

- **Condition**: `i < fruits.Length;` continues the loop as long as `i` is less than the length of the `fruits` array.

- **Iteration**: `i++` increments `i` by 1 after each iteration.


**Output**:

```

apple

banana

cherry

```


#### Example 3: Calculating the Sum of Array Elements


Here is an example of a `for` loop in C# that calculates the sum of numbers in an array:


```csharp

using System;


class Program

{

    static void Main()

    {

        int[] numbers = { 1, 2, 3, 4, 5 };

        int sum = 0;

        for (int i = 0; i < numbers.Length; i++)

        {

            sum += numbers[i];

        }

        Console.WriteLine("Sum: " + sum);

    }

}

```


**Explanation**:

- **Initialization**: `int i = 0;` initializes the loop control variable `i` to 0.

- **Condition**: `i < numbers.Length;` continues the loop as long as `i` is less than the length of the `numbers` array.

- **Iteration**: `i++` increments `i` by 1 after each iteration.

- **Sum Calculation**: `sum += numbers[i];` adds the current array element to `sum`.


**Output**:

```

Sum: 15

```


### Summary


A `for` loop in C# is a powerful construct for iterating over sequences and executing code repeatedly based on a specified condition. It consists of initialization, condition, and iteration parts, making it versatile for a wide range of applications from simple counting to complex data processing.

No comments:

Post a Comment

Thanks for the contribution, our team will check and reply back if response required.