Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Part 15 - C# Tutorial - for and foreach loops in c#

Part 15 - C# Tutorial - for and foreach loops


  1. Hi Venkat,

    I am playing with the foreach loop to tray and make it more flexible in the code below. You'll notice i've commented out a variable k. When I used this variable my code runs correctly. I have now however tried to achieve the code without the variable k and instead just using the i varable in the foreach loop to the same affect, but it gives me the incorrect answer. Can you explain this?

    class Program
    static void Main(string[] args)
    Console.WriteLine("Enter Number:");
    int count = int.Parse(Console.ReadLine());

    int[] number = new int[count];
    int sum = 0;
    //int k =0;

    foreach (int i in number)
    number[i] = (i+1)*10;
    //number[i] = (i + 1) * 10;
    sum += number[i];
    Console.WriteLine("Number: {0}", number[i]);
    Console.WriteLine("Sum: {0}", sum);

    1. There is no need to use number array for processing instead use variable i in the foreach loop.

  2. Hi Venkat,

    You're doing an amazing job with the videos. Thanks a lot!

    I think there might be an additional difference between the for and the foreach loop, and please correct me if I'm wrong.

    If you iterate through a collection of items using the foreach loop, you can't modify the actual items. You can only make use of the information they contain.

    To modify the actual items, I think one should use a for loop instead because referring to the items by their indexes allows the developer to modify them.

    What do you think?

  3. Venkat! it was difficult to me for selecting my future field but once i dig into your tutorials it makes me easy to select DOT-NET as my future field thanks a lot Venkat!

  4. Dear Venkat, You videos are very helpful for me, I am a non-developer and comes from Infra support, I can easily write basic C# programs with by seeing your videos. Thanks a lot


If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.