I am having problem in writing the code for the problem "To assign the elements of 1-D integer array into 2-D array of integers such as if the array is 1,2,3,4,5,6 The resultant 2-D array should be like :
1 0 0 0 0 0
1 2 0 0 0 0
1 2 3 0 0 0
1 2 3 4 0 0
1 2 3 4 5 0
1 2 3 4 5 6
"
I really don't know how to begin at least give me some clue.
Thanks guys.
You will have to use nested for loops to traverse both arrays:
1 2 3 4 5 6 7 8 9 10 11 12
int single_arr[6] = {1,2,3,4,5,6};
int multi_arr[6][6];
for (int i=0; i<6; i++) //loop single array]
{
//single_array[i] is the current element
for (int j=0; j<6; j++)
{
//multi_arr[i][j] refers to current element
}
}
I've already given away a little bit more than I'd like, so I hope that helps.
int single_arr[6] = {1,2,3,4,5,6};
int multi_arr[6][6];
for (int i=0; i<6; i++) //loop single array]
{
//single_array[i] is the current element
for (int j=0; j<6; j++)
{
if((i==1)&&(j==1))
multi_arr[i][j]=single_arr[j];
elseif((i==2)&&(j==1||j==2)); //going on like this for all values
multi_arr[i][j]=single_arr[j]; //and in the end for else
//statement putting multi_arr[i][j]=0
}
}
But this would be inefficient and wouldn't work for the array of unknown size. So, a bit more hint would be helpful
If it needs to work for arrays of variable sizes, you will need to do the following:
- Ask the user how large the single array needs to be
- Create a dynamic array of that size
- Fill that array
In code:
1 2 3 4 5 6 7 8 9
int single_array_size;
//ask size
std::cout << "Size of single array: ";
std::cin >> single_array_size;
//create array
int single_array = newint[single_array_size];
//fill array
for (int i=0; i<single_array_size; ++i)
single_array[i] = i+1;
You could even replace those if statements with 2 more for loops, one to fill up to the position i, the other to write 0 to the remaining positions. But, I'll leave that for you to figure out.
For completeness, I should mention that filling containers in this way can be done easily using the C++11 iota algorithm: http://en.cppreference.com/w/cpp/algorithm/iota