Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't figure out the function for filling array with random numbers c++

So I am trying to make a function randBetween that is going to generate random numbers and after fill the array with those numbers

Problem that I missing out on something when I try to move a statement into function

#include <iostream>
#include <ctime> 
using namespace std;

void fillArray(int arr[], int size, int min, int max);
int randBetween(int max, int min);
void printArray(int arr[], int size);
const int size = 10;

int main()
{
    int arr[size];
    
    int min = -100;
    int max = 100;
    srand(time(NULL));
    
    fillArray(arr, size, min, max);
    printArray(arr, size);
    
}

int randBetween(int max, int min)
{
    
    int num = (rand() % (max - min + 1)) + min;
    return num;
}

void fillArray(int arr[], int size, int min, int max)
{
    
    for (int i = 0; i < size; i++)
    {
        
        int num = 0;
        
        randBetween(min, max);
        //num = ( rand () % (max - min + 1)) + min;
        
        arr[i] = num;
        
    }
}

void printArray(int arr[], int size)
{
    for (int count = 0; count < size; count++)
    {
        cout << arr[count] << "\n";
    }
}

if I don’t comment out //num = ( rand () % (max – min + 1)) + min; it works perfect without function
however I must use it in the functions and I cant figure out what I do wrong;
I tried to change parameters, change location but nothing helps

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Replacing num = ( rand () % (max - min + 1)) + min; with randBetween(min, max); is missing something crucial: You aren’t setting the num variable in the second case. Although you do set num inside the randBetween function, this is actually not the same variable; it’s defined inside randBetween, so it’s not reachable outside of it, and doesn’t effect the num inside fillArray. You can fix this by setting the outer num using this line:

num = randBetween(min, max);

instead of just randBetween(min, max);.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading