today i was learning about jagged arrays.So i wrote the following code, i wanted to use foreach loop with it, but i am getting following error:
Cannot convert type 'int[]' to 'int' on line 31.
The code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ArraysExplained
{
    class Program
    {
        static void Main(string[] args)
        {
           //use of jagged arrays 
            int[][] jaggedarray = new int[3][];
            jaggedarray[0] = new int[4];
            jaggedarray[1] = new int[2];
            jaggedarray[2] = new int[3];
            // it means there are 3 rows , in the first row jaggedarray[0] has 4 elements
            //in the second row i.e jaggedarray[1] has 2 elements
            // in the third row i.e jaggedarray[2] has 3 elements
            //store value in first row
            for (int i = 0; i < 4; i++)
                jaggedarray[0][i] = i;
            //store value in second row
            for (int i = 0; i < 4; i++)
                jaggedarray[1][i] = i*2;
            //store value in third row
            for (int i = 0; i < 4; i++)
                jaggedarray[2][i] = i-1;
            //display jagged array, it can be displayed row by row or it can be 
            //displayed using foreach loop
            foreach (int x in jaggedarray)
                Console.Write(" "+ x);
             

        }
    }
}

i am not able to figure out how to remove that error,also any help is appreciated.

Recommended Answers

All 2 Replies

How about:

foreach (int[] xa in jaggedarray)
         {
            foreach (int x in xa)
            {
               Console.Write(" " + x);
            }

            Console.WriteLine();
         }

Also, instead of using the number 4 as your upper bounds, you sould use the .Length property of the array element:

for (int i = 0; i < jaggedarray[0].Length; i++)
   jaggedarray[0][i] = i;

How about:

foreach (int[] xa in jaggedarray)
         {
            foreach (int x in xa)
            {
               Console.Write(" " + x);
            }

            Console.WriteLine();
         }

Also, instead of using the number 4 as your upper bounds, you sould use the .Length property of the array element:

for (int i = 0; i < jaggedarray[0].Length; i++)
   jaggedarray[0][i] = i;

Ok thanks i got it.Also thanks for rectifying the mistake at using 4, actually using 4 at 2nd and 3rd loop was wrong.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.