1

I am a complete beginner in C and I'm sorry in advance for a trivial question. Q: I would like to return the value of random_num variable that is calculated in number_generator function to the main function:

int main() //didn't paste headers and prototype 
{
   int random_num; // <= to here
   number_generator(random_num);
   printf("random number: %d", random_num);

   return 0;
}

int number_generator(int random_num)
{
   srand(time (0));
   random_num = (rand() % 100) + 0; // <= return value from here
} 

Currently, the terminal output of printf is 0 while it should be in a range from 0 to 100.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • 1
    Spend a bit of time reading your C tutorial or whatever, until you get to the part about the `return` statement. You could also assign via pointer dereferencing but there is no point in this case and that's a more intermediate topic. – Iguananaut Jun 17 '22 at 10:53
  • In other words, all you need here is `return (rand() % 100) + 0;`. Your function doesn't need to take an argument. – Iguananaut Jun 17 '22 at 10:55
  • I suggest that you read this: [srand() — why call it only once?](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once). As soon as you change your program to call `number_generator` more than once, you will also be calling `srand` more than once. That is why it is better to move the call to `srand` to the start of the function `main`. – Andreas Wenzel Jun 17 '22 at 11:34

1 Answers1

2

Do it the following way

int number_generator(void )

int main() //didn't paste headers and prototype 
{
   int random_num = number_generator(); // <= to here
   printf("random number: %d", random_num);

   return 0;
}

int number_generator(void )
{
   srand(time (0));
   return (rand() % 100) + 0; // <= return value from here
}

Another approach is the following

void number_generator(int *random_num);

int main() //didn't paste headers and prototype 
{
   int random_num; // <= to here
   number_generator( &random_num);
   printf("random number: %d", random_num);

   return 0;
}

void number_generator(int *random_num)
{
   srand(time (0));
   *random_num = (rand() % 100) + 0; // <= return value from here
} 

Pay attention to that adding 0 in this expression

(rand() % 100) + 0

does not make a sense. It is equivalent to

(rand() % 100)
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335