how can i create a square 2d array of size nxn where n is supplied by the user and populated with random numbers at a certain range?

You probably should use a vector of vector of ints, using std::vector.

#include<iostream>
#include <random>
#include<time.h>
#include<iomanip>
#include <vector>
#include <map>

using namespace std;

// generate the array with random numbers 
    
void array_gen(vector<vector<int>> & array, size_t arraysize)
{
  array.resize(arraysize);
  for (auto& line : array)
    line.resize(arraysize);

  for (size_t i = 0; i < arraysize; i++)
  {
    for (size_t j = 0; j < arraysize; j++)
    {
      array[i][j] = rand() % -12 + 8;    // generate numbers from 0 to 10 
    }
  }
}

void arraydis(const vector<vector<int>> & array)
{
  for (size_t i = 0; i < array.size(); i++)
  {
    for (size_t j = 0; j < array.size(); j++)
    {
      cout << array[i][j] << " ";
    }
    cout << "\n";
  }
}    

int main()
{
  int arraysize = 0, i;
  cout << "Enter array in the range of 50 <= size <= 200: ";    // records the users input 
  cin >> arraysize;

  vector<vector<int>> array;
  array_gen(array, arraysize);

  cout << "unSorted array is:\n";      // shows the unsorted array 
  arraydis(array);
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top