Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a function that fills a dynamic, n x n array with integers from 1 to n x n

ID: 3575674 • Letter: W

Question

Write a function that fills a dynamic, n x n array with integers from 1 to n x n exactly. The array contains no duplicates. Use the array you created in problem 1 to create the array.

The function's prototype is

void randomFillUnique(int** a, int n);

Write a program to test your function.

.here is my code for problem 1

#include <iostream>
#include <string>
#include <time.h>

using namespace std;
int ** gen2Array(int n);

int main()
{
   int** result = gen2Array(5);
   /* initialize random seed: */
   srand(time(NULL));
   for (int i = 0; i<5; i++)
       for (int j = 0; j<5; j++)
       {
           result[i][j] = 5;
       }
   for (int i = 0; i<5; i++)
   {
       for (int j = 0; j<5; j++)
           cout << result[4][4] << " ";
       cout << endl;
   }
   system("pause");
   return 0;
}
int ** gen2Array(int n)
{
   int **p;
   p = new int*[n]; // dynamic `array (size 4) of pointers to int`

   for (int i = 0; i < n; ++i) {
       p[i] = new int[n];
       // each i-th pointer is now pointing to dynamic array (size 10) of actual int values
   }
   return p;
}

Explanation / Answer

Please find the required program along with its output. Please see the comments against each line to understand the step.

#include <iostream>
#include <string>
#include <time.h>
using namespace std;
int ** gen2Array(int n);


void randomFillUnique(int **a, int n){
  
int c = 1; //initialize a variable to store the array values incrementally
  
for (int i = 0; i<n; i++) { //loop to iterate n no:of rows
for (int j = 0; j<n; j++) //loop to iterate n no:of columns
{
a[i][j] = c; //store the count variable
c++; //inrement the count variable
}
}
  
}

int main()
{
int n = 5;
int** result = gen2Array(n);
  
randomFillUnique(result,n);
  

cout << "Generated array : " << endl;
  
for (int i = 0; i<n; i++){ //for ptinting the generated array
for (int j = 0; j<n; j++)
{
cout << result[i][j] << " " << flush;
}
cout << endl;
}
return 0;
}


int ** gen2Array(int n)
{
int **p;
p = new int*[n]; // dynamic `array (size 4) of pointers to int`
for (int i = 0; i < n; ++i) {
p[i] = new int[n];
// each i-th pointer is now pointing to dynamic array (size 10) of actual int values
}
return p;
}

-----------------------------------------------------------------------

OUTPUT:

Generated array :
1   2   3   4   5  
6   7   8   9   10  
11   12   13   14   15  
16   17   18   19   20  
21   22   23   24   25

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote