logan logan - 11 days ago 5
C++ Question

C++ ArraysWrite a program that creates an array of five random integer numbers and then displays the numbers

I'm in the beginning stages of learning how to program and I'm teaching myself.

Write a program that creates an array of five random integer numbers and then displays the numbers. The program should use an array declared as a global variable. Two functions voidArray and voidPrint

Initializes an array with random numbers between 1 and 1000
Print the of array

void voidArray()
{
srand (time(NULL));
randNum = rand()%100+1;

}


This is the code so far. I know that its wrong. I'm really confused on how I would write code for the voidArray and main functions and the answer is not in my book.

Answer

A popular way in generating random numbers is using srand() and rand() from <cstdlib> and time() from <time>. Let's say you have your array,

int random[5];

Filling random with 1-1000 random numbers in voidArray().

void voidArray() {
    srand(time(NULL));                       // initialize random seed
    for(int index = 0; index < 5; index++)   // fill the array
          random[index] = rand() % 1000 + 1;  
}

Printing will also have the same loop mechanism (from 0 index to 4).

void voidPrint() {
    for(int index = 0; index < 5; index++)
         std::cout << random[index] << " ";
}

Calling consecutively in main().

int main() {
    voidArray();
    voidPrint();
}

You can read about C++11's <random> and experiment even more.