C# For Loop

HTML
CSS
Bootstrap
JavaScript
C#
SQL
Salesforce Admin
Exercise
Study Material

For and Foreach Loop in C#

For Loop

In C#, a for loop is a control flow statement that allows you to execute a block of code repeatedly based on a specified condition. It’s typically used when you know how many times you want to repeat a block of code.

Basic structure:

for (Set Value; Check condition; increment/decrement)

        {
            // write the Code block to execute in the for loop
        }

For Loop example:

Loop 1 (i=1):

The code initializes a variable i to 1 (i = 1). The condition is checked to see if i <= 4. Since i=1 is less than or equal to 4, the code block is executed, and the console prints the output as “i value: 1”. Now i will be incremented by 1, so i becomes 2.

Loop 2 (i=2):

i is now 2, and the condition is checked again. Since i=2 is less than or equal to 4, the code block is executed, and the console prints the output as “i value: 2”. Now i will be incremented by 1, so i becomes 3.

Loop 3 (i=3):

i is now 3, and the condition is checked again. Since i=3 is less than or equal to 4, the code block is executed, and the console prints the output as “i value: 3”. Now i will be incremented by 1, so i becomes 4.

Loop 4 (i=4):

i is now 4, and the condition is checked again. Since i=4 is less than or equal to 4, the code block is executed, and the console prints the output as “i value: 4”.

Loop 5 (i=5):

i is now 5, and the condition is checked again. Since i=5 is not less than or equal to 4, the loop will end.

For loop Statement

Scenario : Sum of all number from 1 to 5 i.e. 1 + 2 + 3 + 4 + 5 = 15 using for Loop i.e define the loop from 1 to 5

using System;

public class SumOfNumbers

{

    public static void Main(string[] args)

    {

        int sum = 0;

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

        {

            sum += j;

        }

        Console.WriteLine("Sum of numbers from 1 to 5: " + sum);

    }

}

Output : Sum of numbers from 1 to 5: 15

Code Explanation

using System;

public class SumOfNumbers

It defines a new class with named – SumOfNumbers.

{

    public static void Main(string[] args)

This is the entry point of the program

{

        int sum = 0;

It declares a variable named sum of type integer and assigns it the value 0.

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

This is a for loop that run from j = 1 to j = 5. The loop has three parts:

1. Initialization: Assigning the value 1 to variable name j which type is int (int j = 1)

2. Checking the condition: j is smaller or equals to 5 (j <= 5),

3. Increment/Decrement (j++): In each iteration, j increases by 1 by using j++. In for loop for each iteration the code in the between { } will be executed

{

            sum += j;

In above code Sum + = j is the syntax for adding the j variable value in existing sum variable   to get a new sum variable i.e. it adds the current value of j to the sum variable like –> sum = sum + j

1st iteration : Sum + =j (Sum=0 , J=1 so 0+1 = 1 will be saved in sum variable

2nd iteration : Sum + =j (Sum=1 , J=2 so 1+2 = 3 will be saved in sum variable

3rd iteration : Sum + =j (Sum=3 , J=3 so 3+3 = 6 will be saved in sum variable

4th iteration : Sum + =j (Sum=6 , J=4 so 6+4 = 10 will be saved in sum variable

5th iteration : Sum + =j (Sum=10 , J=5 so 10+5 = 15 will be saved in sum variable

6th iteration : Loop will check condition J<=6 hence j=6 i.e. the j is not less then 5 or equals to 5 so loop will end.

}

        Console.WriteLine("Sum of numbers from 1 to 5: " + sum);

After the loop end , this line prints the sum of numbers from 1 to 5 to the console.

}

}

Output : Sum of numbers from 1 to 5: 15

You will see the above output on your console.

Foreach Loop

In C#, the foreach loop is used to iterate over elements in a collection or array. It simplifies the process of iterating through each element of a collection without needing to keep track of indices or the length of the collection manually.

Basic structure

local variable

foreach (var item in collection)

        {

            // Statements to be executed for each item in the collection e. collection is (14, 8, 21, 5, 37, 2)

        }

The loop starts, and for the first iteration, it assigns the first element of the collection array to the local variable .

The code inside the loop body is executed using the value of the first element (local variable) from the array.

After completing the code execution for the first element, the loop moves to the next element in the array.

This process continues until all elements in the array have been processed.

The loop automatically handles the iteration and termination After processing all elements in the array, the loop terminates.

Foreach Loop Statement

Scenario : Write a C# program using foreach loop that finds the maximum value from an array of integers and prints it to the console

using System;

public class FindMaxNumber

{

    public static void Main(string[] args)

    {

        int[] Collectionofnumbers = { 14, 8, 21, 5, 37, 2 };

        int max = Collectionofnumbers [0];

        foreach (var number in collectionofnumbers)

        {

            if (number > max)

            {

                max = number;

            }

        }

        Console.WriteLine("The maximum value in the array is: " + max);

    }

}

Output: The maximum value in the array is: 37

Code Explanation

using System;

public class FindMaxNumber

It defines a new class named – FindMaxNumber.

{

    public static void Main(string[] args)

It defines the entry point of the program

{

        int[] Collectionofnumbers = { 14, 8, 21, 5, 37};

It declares a variable named Collectionofnumbers of type integer array and assigns it Five integer values – (14, 8, 21, 5, 37)

        int max = Collectionofnumbers[0];

It declares an integer variable max with the first index value i.e. 0  of the Collectionofnumbers array. 14 is the number at index 0. The first element of the array is the maximum initially.

foreach (var number in Collectionofnumbers)

        {

This is a foreach loop that runs over each element in the Collection of numbers array. It assigns each element to the variable number one at a time from numbers.

1st iteration: It will take the max value at index 0 i.e. 14; hence, max = 14 & number = 14; if the condition number is not greater than max, i.e. in our case, the number = max = 14, a block of code will skip and continue iteration.

2nd iteration: It will take the max value at index 0, i.e. 14; hence, max = 14 & number = 8 if the condition number is not greater than max, i.e. in our case, the number = 8 & max = 14 so the if block of code will skip and continue iteration.

3rd iteration: It will take the max value at index 0, i.e. 14; hence, max = 14 & number = 21 if the condition number is now greater than max, i.e. in our case, the number = 21 & max = 14 so the if block of code between { } execute and set max variable value = 21 and continues iteration

4th iteration: It will take the max value, the max value now of index 2 is 21, hence max =21 & number = 5, if the condition number is not greater than max, i.e. in our case now max = 21 & number = 5 then the if a block of code will skip and continue iteration.

5th iteration: It will take the max value; the max value is now of index is 21 hence max = 21 & number = 37 if the condition number is now greater than max, i.e. in our case, max = 21 and number = 37 so if a block of code between { } will execute and set max variable value = 37 and end iteration

6th iteration: It will not iterate because there is no 6th element in Collection of numbers.

            if (number > max)

It checks if the current element (number) is greater than the current maximum value (max variable value)if yes then it will execute if block code otherwise skips if block.

{

                max = number;

This line assigns the value of the number to the variable max. If the number is greater than max.

}

        }

        Console.WriteLine("The maximum value in the array is: " + max);

This line prints the maximum value to the console which we found in the numbers array

    }

}

Output: The maximum value in the array is: 37

You will see the above output on your console.

Course Video

Practices Tasks

1. You need to create a program that prints the multiplication table of a given number using a for loop. The program should display the multiplication table from 1 to 10 for the specified number.

First you have to take input from console

After giving input you have to show like this same as below 

2. Write a program in C# to show all even numbers between 1 to 10 using a for loop. 

Iterate through numbers from 1 to 10 using a for loop and then check in if condition that

 i % 2 == 0 if yes then show in console like same as below 

3. You have a list of products that a customer has added to their cart, So  you have to check collection of items which added in their shopping cart by using foreach loop.

First you have to create a list of items in a string format and then show ouput Same as below using foreach loop

4. Use a foreach loop to iterate over a list of employee objects and calculate their monthly salaries based on hourly rates and hours worked.

First you have to create a list of employee and define in list name rates hours and workly hours then you have to multiply  hourly rates and hourly worked and then ouput should print same as below