Hi, im having some problem while doing my assignment,
i cant make my recursive function to loop as to get each digit from the number generated randomly.

``````int random (int num)
{

srand (time (NULL));
num = rand();
cout << num << endl;

if (num != 0)
return num % 10;
num = num / 10;
}
``````

Wat im trying to do here is to get each digit from the number, for example, number show is 3859, i should get the result of 9 5 8 3.
But from my coding i'll only get the last digit, that's 9.

Thanks

Edited by Nick Evan: Fixed formatting

4
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by Denniz

Hi, im having some problem while doing my assignment,
i cant make my recursive function to loop as to get each digit from the number generated randomly.

``````int random (int num)
{

srand (time (NULL));
num = rand();
cout << num << endl;

if (num != 0)
return num % 10;
num = num / 10;
}
``````

Wat im trying to do here is to get each digit from the number, for example, number show is 3859, i should get the result of 9 5 8 3.
But from my coding i'll only get the last digit, that's 9.

Thanks

One, you're going to get really lousy random numbers since you keep seeding the random number generator. Just seed it once at the top of the program. Two, there's no reason to pass this function anything. num is immediately overwritten at the top of the function before you do anything with it, so its value is lost. Three, this isn't a recursive function. Four, please use code tags.

Edited by pyTony: fixed formatting

``````int random (int num)
{

srand (time (NULL));
num = rand();
cout << num << endl;

if (num != 0)
return random(num % 10);
num = num / 10;
}``````

Ok..
where exactly i should put the random generator?
Then, can u help me how to use recursive loop here?

``````int random (int num)
{
srand (time (NULL));
num = rand();
cout << rand() << endl;
int n = m;
cout << n << endl;

if (num != 0)
return num % 10;
num = num / 10;``````

Thanks.

Ok..
where exactly i should put the random generator?
Then, can u help me how to use recursive loop here?

``````int random (int num)
{
srand (time (NULL));
num = rand();
cout << rand() << endl;
int n = m;
cout << n << endl;

if (num != 0)
return num % 10;
num = num / 10;``````

Thanks.

1. Not all paths in your function returns an integer. You would encounter a warning if you try to compile your code.

2. What's the use of "n" and "m" ?

3. Seed your random generator once in your main function before calling the random function.

4. If what you want is to generate random number, you don't have to use loop or recursive function at all. But it's kind of unclear what you actually wants, so it's better if you can elaborate your requirements.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.