CSharp - A foreach loop and its equivalent for loop.

Description

A foreach loop and its equivalent for loop.

Demo

using System;
using System.Collections.Generic;

class Program/*from   ww  w  . j a va 2  s .  c  o  m*/
{
    static void Main(string[] args)
    {
        List<int> list = new List<int>() { 1, 2, 3, 4, 5 };
        Console.WriteLine("Executing foreach loop");
        foreach (int i in list)
        {
            Console.WriteLine("\t" + i);
        }
        Console.WriteLine("Executing for loop :");
        for (int i = 0; i < list.Count; i++)
        {
            int j = list[i];
            Console.WriteLine("\t" + j);
        }
    }
}

Result

To print the values, like 1,3,5, writing code using the for loop is easier.

We need to change only the increment part of the for loop, as follows (i.e., instead of i++, use i+=2):

for (int i = 0; i < list.Count; i+=2)

Related Topic