0

This is a two fold question. I am trying to build a program were I am able to call a function based on the input of a user. Basically the program will ask the user how many sets of random numbers they would like. And based on their answer I would like to call my function based on their answer. Is that possible? Thanks ! My code is below.

#include<iostream>
#include<stdlib.h>

void randomGenerator()
{
    int i;          //loop counter
    int num;        //store random number

    int randomize();    //call it once to generate random number
    for(i=1;i<=10;i++)
    {
        num=rand()%100; //get random number
        std::cout << num << "\t";
    }

}

int main(){
    randomGenerator();
    return 0;
}

2 Answers2

1

What's wrong with using a loop?

cout << "how many random numbers? ";
int num;
cin >> num;
for (int i = 0; i < num; ++i)
    randomGenerator();

Incidentally

int randomize();    //call it once to generate random number

is a function prototype, not a function call. So you aren't calling that function any number of times.

If you want to call the function once, do it in main before you do anything else and put the prototype at the top of your code, where it belongs.

int randomize();    // here the prototype for randomize

int main()
{
    randomize(); // and here's the call to randomize
    ...
}
john
  • 85,011
  • 4
  • 57
  • 81
-1

in you int main() you have just to add to while lke this

     int main() {
     int times = 0;
     int timeNumber = 0;

     printf("how many randow numbers you want to generate? ");
     scanf("%d",&times);


      while(timeNumber < times)
       { 
         timeNumber++;
         randomGenerator();
       }
       return 0;

     }
Object object
  • 1,939
  • 10
  • 19
  • A for loop would be neater for this, but more importantly don't use `printf` or `scanf` in C++, use `std::cout` and `std::cin` see [this answer](https://stackoverflow.com/a/119194/12448530) as to some reasons why – Object object Apr 01 '20 at 13:22
  • I am a problem solver and scanf and printf have less excution time than cin and cout tha's why i did it like that – Hedi KARRAY Apr 01 '20 at 13:25
  • "less execution time". Nope. Both will be limited by either the human typing speed, or the bus bandwidth on any modern machine – Jeffrey Apr 01 '20 at 13:31
  • `scanf` and `printf` are _marginally_ faster and if you need the performance you will be writing _very_ specilised code. The type safety and integration with the ecosystem (classes can overload stream operators) of `std::cin` and `std::cout` make them the default better option. The best solution is not always the fastest (especially when computers 'slow' is far faster than humans can perceve) – Object object Apr 01 '20 at 13:31