dimanche 31 janvier 2021

Getting Weird Outputs When Printing my 2D Array with Random Numbers, Specifically on Row 6 and 7

My output for the following code has something weird happening on rows 6 and 7, Row 6 always has 3 zeros as the last entries and row 7 always has first 4 zeros and then a large number ~480000. I dont know what is causing this and I need the code to print a full 2D array with 7 rows and 5 columns all with random numbers from 1-100.

#include <iostream>
#include <cstdlib>
using namespace std;   
 //Function precalls
   int random_num(int r);
   void printArray(int * arr, int r, int c);

int main()
{

const int length= 5; //Sets the length of the array segments
int ran=0;
int i,j;
int r=7; //Declares number of rows
int c=5; //Declares number of columns
int arr[7][5]; //Initializes the array
    for(int i=0; i < 5; i++)
    {
        for(int j=0; j < 7; j++)
        {
            arr[i][j] = random_num(ran);
        }
    }
printArray((int*)arr, r, c);
}

    void printArray(int * arr, int r, int c) //Prints the Array
{
for(int i=0; i < r; i++)
{
    for(int j=0; j < c;j++ )
    {
        cout << *(arr+i*c+j) << " ";
    }
    cout<< endl;
 }
}

  int random_num(const int r) //Assigns random numbers to Array
  {

int ran=0; //Sets the number to zero before generation

ran = rand()% 100 + 1;
return ran;

   }



Aucun commentaire:

Enregistrer un commentaire