0

Can anyone please let me know What is difference between "For loop" OR "Foreach loop" & which is faster from both of them?

I searched on internet but can't find any detailed answer with example. :-/

The only difference I found is :-

  • For :- should be used when wants to iterate for a fixed number of times.
  • Foreach :- should be used when wants to iterate through collection.

Please help me out here.

Any help is appreciated. :-)

Thanks.

Archana Parmar
  • 438
  • 3
  • 12
  • for loop can be used to add or remove items and it can iterate in reverse order. foreach is more like for loop everything. – active92 Dec 16 '16 at 04:21
  • You can't add, delete, change item in `foreach` loop, that's one of the important differences between them. – Yurii N. Dec 16 '16 at 05:19

1 Answers1

1

The for loop is a construct that says "perform this operation n.times".

Example -

int n = 5; // You can assign any preferred value  
          for(int i=0; i<n; i++){
             (your operation); // it will be in 5 times
          }

The foreach loop is a construct that says "perform this operation against each value/object in this IEnumerable"

Example -

List<string> names= new List<string>();

        names.Add("Tom");
        names.Add("Denver");
        names.Add("Nash");
        names.Add("Cheruu");
        names.Add("Amy");

        foreach(string name in names)
        {
            Console.WriteLine(name);
        } 

You can find more details from here.

Community
  • 1
  • 1
Thili77
  • 951
  • 11
  • 19