In: Computer Science
write a program which will prompt an array of 12 integers then print the array as an array of 4 columns on 3 rows
/* First we will store these 12 integers in an array . After this we will create a two dimensional array of size 3 x 4 and then print the content of the 2 D array */
/*
1. Create a 1 dimensional array and insert any 12 elements into
it.
2. create a dynamic 2 dimensional array of size 3 x 4
3. insert content of previous array into the dynamic array
using
array2d[i][j]=array1d[(j*row)+i]
4. print content of 2 D array two loops
if random numbers inserted into original array is :
83 86 77 15 93 35 86 92 49 21 62 27
then ,its output will be like :
83 15 86 21
86 93 92 62
77 35 49 27
4 columns and 3 rows
*/
/* c++ code of the above algorithm */
#include<bits/stdc++.h>
using namespace std;
int main()
{
int arr1d[12];
for(int i=0;i<12;i++)
// inserting any random no (0
to 99)
arr1d[i]=rand()%100;
// into 1 D array
// you can take any integer values
for(int i=0;i<12;i++)
cout<<arr1d[i]<<"
"; //checking
content of 1 D array
cout<<endl;
int row=3, column=4;
// forming a dynamic 2 D
array of
int *array2d[row];
// given
size(standard approach)
for(int i=0;i<row;i++)
array2d[i]=(int*)malloc(column*sizeof(int));
for(int i=0;i<row;i++)
// copying
contents from 1 D array
{
for(int
j=0;j<column;j++)
array2d[i][j]=arr1d[(j*row)+i];
// array2d[i][j]=ith row and jth column
}
for(int i=0;i<row;i++)
//
Displaying contents of 2 D array
{
for(int j=0;j<column;j++)
cout<<array2d[i][j]<<" ";
cout<<endl;
}
return(0);
}