Search code examples
dev-c++

Having trouble with converting this one dimensional array to a two dimensional array in C++


This is a program that asks a user to input 20 numbers then arranges them in a 2-dimensional array with ascending order. I'm having trouble with converting the 1 dimensional array into a 2 dimensional array. The output results into a two dimensional array with the same values.

        #include<iostream>
        #include<iomanip>
        using namespace std;

        //global
        int i,j,count;
        int row,col;
        const int sizeRow=4;
        const int sizeCol=5;
        int list[sizeRow][sizeCol];
        int elements[20];
        int temp;

        int main()
        {

            cout<<"Processing Bubble Sorting Technique..."<<endl
            <<"Enter 20 elements"<<endl;  
        
            for (i=0;i<20;i++) //input
            {
                cout<<"loc["<<i<<"]:";
                cin>>elements[i];
                cout<<endl;
            }

            for (i=0;i<20;i++) //process-bubble sorting
            {
                for (j=i+1;j<20;j++)
                {
                    if (elements[j]<elements[i])
                    {
                        temp=elements[i];
                        elements[i]=elements[j];
                        elements[j]=temp;
                    }
                }
            }
            //converting 1 dimensional array to 2 dimensional
            cout<<"Ascending Order"<<endl;
            for (count=0;count<20;count++)
            {
                for (i=0;i<sizeRow;i++)
                {
                    for(j=0;j<sizeCol;j++)
                    {
                    list[i][j]=elements[count]; 
                    }
                }
            }   
            //output
            for (i=0;i<sizeRow;i++)
            {
                for(j=0;j<sizeCol;j++)
                {
                    cout<<left<<setw(5)<<list[i][j]<<" ";
                }
                cout<<endl;
            }
        }

Solution

  • It's your triply-nested loop. Think about it; that going to assign EACH element to EVERY element of the outgoing array.

    You want:

    for (count=0;count<20;count++)
    {
        int i = count / sizeCol;
        int j = count % sizeCol;
        list[i][j]=elements[count]; 
    }