Hi Friends...
I used for loop many times but I want to know difference between for and foreach loop in C# ? Please explain with an example ?
Thanks.....
Loading
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Satyapriya NayakPosted Feb 4, 2012, 11:47 PM
for loop
The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false. The for loop is useful for iterating over arrays and for sequential processing
Because the test of a conditional expression occurs before the execution of the loop, a for statement executes zero or more times.
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace For_foreach_loop
{
class Program
{
static void Main(string[] args)
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
For Each loop is used to iterate through arrays or collections.
foreach loop
The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the desired information, but should not be used to change the contents of the collection to avoid unpredictable side effects.
Example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace For_foreach_loop
{
class Program
{
static void Main(string[] args)
{
int[] arr1 = new int[] { 0, 1, 2, 3, 4, 5, 6 };
foreach (int i in arr1)
{
Console.WriteLine(i);
}
Console.ReadLine();
}
}
}
Thanks
Vineet Kumar SainiPosted Feb 5, 2012, 1:46 AM
Posted Feb 4, 2012, 11:42 PM
Please watch the above video in YouTube.
Prime bPosted Feb 4, 2012, 11:09 PM
http://www.csharp-station.com/Tutorials/Lesson04.aspx
http://www.c-sharpcorner.com/UploadFile/abanerjee/ForEach11092005004606AM/ForEach.aspx