for and foreach loop in C#

for loop:

  1. for loop's variable will always be an integer.

  2. The for loop executes the statement or block of statements repeatedly until specified expression evaluates to false.

  3. In for loop we have to specify the loop's boundary ( maximum or minimum). We can say that this is the limitation of the for loop.
Syntax:

    for (Initialization;condition;Increment)
    {
    //….Statement
    }

For Example:

  1. for(int I =0; I <= 20; I++)  
  2. {  
  3.         if(I%2 == 0)  
  4.          {  
  5.             Console.WriteLine(“Even Numbers {0}”,I);  
  6.          }  
  7. }  
foreach loop: 
  1. In case of foreach loop the variable of the loop will be same as the type of values under the array.

  2. The foreach statement repeats a group of embedded statements for each element in an array or an object collection.

  3. In foreach loop, You do not need to specify the loop bounds minimum or maximum.

    Here we can say that this is an advantage of for each loop.

Syntax:

    foreach ( )
    {
    // statments
    }

For Example:
  1. string[] AnimalNames = new string[] "Dog","Tiger","Panda","Penguin" }  
  2. foreach (string animal in AnimalNames)  
  3. {   
  4.   Console.WriteLine(“Name of animal is 0}“,animal);  
  5.   
  6. }    
Example for both for and foreach loop
  1. using System;  
  2. namespace ConsoleApplication1  
  3. {  
  4.     class Program  
  5.     {  
  6.         static void Main(string[] args)  
  7.         {  
  8.             int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };  
  9.   
  10.             //For each loop  
  11.             Console.WriteLine("Foreach loop");  
  12.             foreach (var item in num)  
  13.             {  
  14.                 Console.WriteLine(item);  
  15.             }  
  16.   
  17.             //for loop  
  18.             Console.WriteLine("For loop");  
  19.             for (int i = 1; i <= num.Length; i++)  
  20.             {  
  21.                 Console.WriteLine(i);  
  22.             }  
  23.   
  24.             Console.ReadKey();  
  25.   
  26.         }  
  27.     }  
  28. }  
Output

output

Summary

In this blog you learnt about difference between foreach and for loop.
Thanks for reading.