Monday, December 14, 2015

Difference between for and foreach loop in c#?


This is very basic question asked in many interview. I will explain in detail.
1.       The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false.  There is need to specify the loop bounds( minimum or maximum).
int j = 0;
for (int i = 1; i <= 5; i++)
{
j = j + i ;
}

                The foreach statement repeats a group of embedded statements for each element in an array or an object collection. You do not need to specify the loop bounds minimum or maximum.
int j = 0;
int[]  myArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in myArr )
{
j = j + i ;
}
2.       foreach -> Treats everything as a collection and reduces the performance. foreach creates an instance of an enumerator (returned from GetEnumerator()) and
          that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.
        3.  Using for loop we iterate the array in both direction, that is from index 0 to 9 and from 9 to 0.
        But using for-each loop, the iteration is possible in forward direction only.
       4. In variable declaration, foreach has five variable declarations (three Int32 integers and two arrays of Int32) while for has only three (two Int32 integers and one Int32 array).
           When it goes to loop through, foreach copies the current array to a new one for the operation. While for doesn't care of that part.

               Interviewer asked me 2  scenario based question in one interview:
         a.   for (int i = 1; i <= 5; i++)
             {
               i = i + i;
             }
                          The above code will work?
                         Yes this will work.
        b.  int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
            foreach (int i in tempArr)
            {
                i = i + 1;
     }
Above code will work?
This code will not compile. I have pasted screenshot of error.




I hope it will help somebody in interview.

No comments:

Post a Comment

Write a program to reverse a string? using System; namespace ConsoleApp1 {     class Program     {         static void Main(string[] args)  ...