# decreasing variable

• 01-07-2003
decreasing variable
hi there i just wrote the following code.
Code:

void case3()
{
int i;
puts("here are your lottery numbers: ");
for(i=0;i<6;i++)
{
int a=rando();
if (a == a && a == 0)
i=i-1;
else
printf("%d ", a);
}
}

with this for statement i want to start a loop that generates 6 random and different numbers.
i tried to kill the same numbers with that if statement whats supposed to proof if the same value is given or 0, if so it should decrease i by one and start from the beginning.
but actually it doesnt do that, it goes on printing zeros and the same values.
whats wrong? :confused:

help would be greatly appreciated
• 01-07-2003
Hammer
How about finding a way to "remember" the numbers you've already generated...

Also, you'll want to get numbers between 1 and 50 (or whatever), I guess, so different method of getting random numbers is needed. That way, you won't need to check for 0.

Also, there's various examples of this on the forums here, try a search and see what you can find.
• 01-07-2003
the rando() function returns a value from 0 to 49.
i was just wondering why it didnt work that way. can you give me
an example how it would work my way?

thanks
• 01-07-2003
Hammer
Oopps, sorry, I didn't see it was rando(), I thought it was rand(), hence my comments.

If your own version (rando) gives you 0 - 49, and you don't want 0, why not fix it so it gives you 1 - 49.
• 01-07-2003
Prelude
>with this for statement i want to start a loop that generates 6 random and different numbers.
Your loop is a bit unusual:

>if (a == a && a == 0)
Of course a is going to be equal to a, you can remove that and just test for 0. Though since you want all different numbers simply testing for 0 doesn't help you much.

Perhaps if you kept a record of the numbers already produced and didn't increment the counter until a new number is found:
Code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static int is_saved ( int val, int *saved, int size )
{
int i;

for ( i = 0; i < size; i++) {
if ( saved[i] == val ) {
return 1;
}
}

return 0;
}

int main ( void )
{
int a, i = 0;
int saved[6];

srand ( (unsigned)time ( NULL ) );

while ( i < 6 ) {
a = rand() % 50;

if ( !is_saved ( a, saved, 6 ) ) {
saved[i++] = a;
}
}

printf ( "Your numbers are: " );

for ( i = 0; i < 6; i++ ) {
printf ( "%d ", saved[i] );
}

printf ( "Your bonus number is: %d\n", rand() % 50 );

return 0;
}

-Prelude
• 01-07-2003