Jump to content

Array Problems

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
4 replies to this topic

#1
jaffemutant

jaffemutant

    Newbie

  • Members
  • Pip
  • 8 posts
i have a question regarding with Arrays:

I am wondering if your able to use a foreach in a multidimensional array. I am able to use a nested for loop to output the information. I am curious about it. I would greatly appreciate the help.

#2
Davide

Davide

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 506 posts
What is the point in using a foreach if you have an array?

Just use two for's:

for (int i = 0; i<n; i++)
     for (int j = 0; j<n; j++)
          Console.WriteLine(array[i][j]);

Are you a newbie programmer trying to learn C#? Check out my small tutorial: Visual C# Programming Basics

#3
jaffemutant

jaffemutant

    Newbie

  • Members
  • Pip
  • 8 posts
I realized that using a foreach is only meant for a single dimensional array. But, I just wanted to make sure that you still can use it for multidimensional

#4
lobo521

lobo521

    Learning Programmer

  • Members
  • PipPipPip
  • 57 posts

Davide said:

What is the point in using a foreach if you have an array?

when you use foreach code is clean. You dont have to declare additional indexing variables.

#5
lobo521

lobo521

    Learning Programmer

  • Members
  • PipPipPip
  • 57 posts
Following code prodcues output: "1234".
Wthout any variable.

    class Program
    {
        static void Main(string[] args)
        {

            var array = new [,] {{1, 2}, {3, 4}};

            foreach (var value in array)
                Console.Write(value);

            Console.Read();
        }
    }