Q.What Difference For Loop and For-Each Loop in C#?
Ans:-
Why Loops
If we want to perform the repetitive tasks “n” number of times or an infinite number of times then it is good practice to use loops.For Loops:
For loops are appropriate loops when you know exactly how many times iteration you want in statements within the loop.For loop iterates a statement or a block of statements repeatedly until a specified expression evaluates to false.
Syntax:
| for (; Boolean-expression;) |
| ….Statement |
| } |
For Example:
| for ( int I =0; I <= 20; I++) |
|
| if (I%2 == 0) |
| Console.WriteLine(“Print Even Numbers 0}”,I); |
| } |
| } |
ForEach Loops
For-each loop is used to iterate through the items in object collections, List generic collections or array list collections.
Syntax:
| foreach ( ) |
|
| ….Statement |
| } |
For Example:
| string [] AnimalNames = new string [] "Dog" , "Tiger" , "Panda" , "Parot" } |
| foreach ( string animal in AnimalNames) |
|
| Console.WriteLine(“Name of animal is 0}“,animal); |
| } |
Difference Between For and For Each Loop
- For loop iterates a statement or a block of statements repeatedly until a specified expression evaluates to false.
- For-each loop is used to iterate through the items in object collections, List generic collections or array list collections.
- Performance: For Loops are faster than For-each Loop. If we iterate array list or any collection with for loop and for-each loop then you will find time consumed by a for-each loop is much more than for loop so For loops are faster than For-each loop.
No comments:
Post a Comment