locked
foreach RRS feed

  • Question

  • Hi,

    I have a prblm like below:


                int[] a = new int[4] {1,2,3,4};
                int[] b = new int[4] {5,6,7,8};
              

                 foreach val1 in  a  AND val2 in b
                  
                {
                    int c = val1 + val2;
                    MessageBox.Show(c.ToString());
                }


    and output to be as  6 8 10 12.

    Can any one tel me how to do that programatically using foreach ?
    Is it possible to use two arrays at a time in foreach ?

    Wednesday, August 5, 2009 8:46 AM

Answers

  • No, you can't use multiple arrays in one foreach loop, but you can do this:

    for (int i = 0; i < a.Length; i++)
    {
        int c = a[i] + b[i];
        MessageBox.Show(c.ToString());
    }

    Geert van Horrik - CatenaLogic
    Visit my blog: http://blog.catenalogic.com
    • Proposed as answer by YiChun Chen Thursday, August 6, 2009 8:43 AM
    • Marked as answer by YiChun Chen Tuesday, August 11, 2009 3:35 AM
    Wednesday, August 5, 2009 9:20 AM