Okay, so I was given this problem for my assignment, and I was wondering if I have completed the tasks the question asks. I would also like to know how I can improve this code as well. Please nothing too fancy as I have just learned arrays.
Question:
Write a method, linearize, that takes a 2-dimensional array as parameter and returns a 1-
dimensional array with all the elements of the two-dimensional array. For example, given the
following array:
10, 20, 30
40, 50, 0
60, 0, 0
The method will return a 1-dimensional array with the following elements:
10, 20, 30, 40, 50, 60
My code:
#include <iostream>//include statement(s)
#include <iomanip>
using namespace std;//using namespace statement(s)
void linearize(int arry[][3], int oneDimArray[]);//void function header linearize to convert 2-d array to 1-d array
int main()
{
int arry[3][3] = {{10, 20, 30}, {40, 50, 0}, {60, 0, 0}};//variable declaration(s), to initialize the array
int oneDimArray[25] = {0};
cout << " Your 2-d array before linearized: " << endl;
for (int row = 0; row < 3; row++)//to create the row(s)
{
cout << endl;
for (int col = 0; col < 3; col++)//to create the column(s)
cout << setw(3) << arry[row][col] << "\t";//print out 2-d array before
}
cout << endl;
cout << endl;
cout << " Your 2-d array after linearized: " << endl;
linearize(arry, oneDimArray);//function call for 1-d array
cout << endl;
cout << endl;
system ("PAUSE");//black box to appear
return 0;//return statment(s)
}
void linearize(int arry[][3], int oneDimArray[])//void unction call to create 1-d array from 2-d array
{
int counter = 0;
for (int row = 0; row < 3; row++)//creates rows
{
for (int col = 0; col < 3; col++)//creates columns
{
if (arry[row][col] != 0)//set the condition for the 1-d array to NOT print 0's
{
counter++;//to create an index for 1-d array
oneDimArray[counter] = arry[row][col];//sets 1-d array to values of 2-d array
cout << setw(3) << oneDimArray[counter];//prints out 1-d array
}
}
}
return;
}
Thank you for feed back! It's much appreciated! :)