for loop:
- for loop's variable will always be an integer.
- The for loop executes the statement or block of statements repeatedly until specified expression evaluates to false.
- 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 Example:
- for(int I =0; I <= 20; I++)
- {
- if(I%2 == 0)
- {
- Console.WriteLine(“Even Numbers {0}”,I);
- }
- }
foreach loop: - In case of foreach loop the variable of the loop will be same as the type of values under the array.
- The foreach statement repeats a group of embedded statements for each element in an array or an object collection.
- 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:
For Example:
- string[] AnimalNames = new string[] "Dog","Tiger","Panda","Penguin" }
- foreach (string animal in AnimalNames)
- {
- Console.WriteLine(“Name of animal is 0}“,animal);
-
- }
Example for both for and foreach loop
- using System;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
-
-
- Console.WriteLine("Foreach loop");
- foreach (var item in num)
- {
- Console.WriteLine(item);
- }
-
-
- Console.WriteLine("For loop");
- for (int i = 1; i <= num.Length; i++)
- {
- Console.WriteLine(i);
- }
-
- Console.ReadKey();
-
- }
- }
- }
Output
Summary
In this blog you learnt about difference between foreach and for loop.
Thanks for reading.