Home > OS >  Can't figure out the function for filling array with random numbers c
Can't figure out the function for filling array with random numbers c

Time:04-29

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

CodePudding user response:

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);.

  • Related