problem: Write a C++ program that declares a 2-dimensional array random[][] of i
ID: 674154 • Letter: P
Question
problem:
Write a C++ program that declares a 2-dimensional array random[][] of integers with three rows and four columns. The program will call a function initialize(float*ptr, int rows, int cols) that accepts as argument a pointer to the array random[][] and the dimensions of the array. This function initializes the array to random values between 0 and 1. It then asks the user to choose between displaying the array (row by row ) or its transpose (row by row). The program will finally call a function displayArray(float*ptr, int rows, int cols, bool t) that displays either the array pointed by ptr (if t=false) or the transpose of the array (if t=true).
Explanation / Answer
#include<iostream>
#include<time.h>
using namespace std;
void initialize(int *ptr, int rows, int cols) {
for (int i=0; i<rows; i++) {
for (int j=0; j<cols; j++) {
ptr[i*cols + j] = rand()%2;
}
}
}
void displayArray(int*ptr, int rows, int cols, bool t) {
if(t) {
for (int i=0; i<cols; i++) {
for (int j=0; j<rows; j++) {
cout<<ptr[j*cols+i]<<" ";
}
cout<<" ";
}
} else {
for (int i=0; i<rows; i++) {
for (int j=0; j<cols; j++) {
cout<<ptr[i*cols+j]<<" ";
}
cout<<" ";
}
}
}
int main() {
srand(time(NULL));
int random[3][4];
int rows = 3;
int cols = 4;
initialize(&random[0][0], rows, cols);
cout<<"Enter 0 to print the array or 1 to print the array in transpose ";
cout<<"Enter :";
int ch;
cin>>ch;
cout<<" ";
if(ch==0) {
cout<<"Array: ";
displayArray(&random[0][0], rows, cols, false);
}
else {
cout<<"Array in transpose: ";
displayArray(&random[0][0], rows, cols, true);
}
cout<<" ";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.