generating 10 unique random numbers in C
Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i=0,j=0,n=0,a[10],flag=-1;
for(i=0;i<10;i++)
{
a[i]=-1;
}
while(i<10)
{
n=rand()%10;
for(j=0;j<10;j++)
{
if(n==a[j])
{
flag=0;
break;
}
else
{
flag=1;
}
}
if(flag==1)
{
a[i]=n;
i++;
}
}
for(i=0;i<10;i++)
{
printf("%d\n",a[i]);
}
}
when i compile and run the above code I get -1.
it should generate 10 unique random numbers between 10, but it does not...
i use gcc this is the output
Code:
$ gcc random.c
$ ./a.out
-1
-1
-1
-1
-1
-1
-1
-1
-1
-1
Re: generating 10 unique random numbers in C
after the first for loop the "i" variable equals 10, so the while loop never run.
By the way, if you had stepped through your code with the debugger you'd have seen it immediately.
Re: generating 10 unique random numbers in C
its really pathetic of me...
please mods...lock and delete this thread...
i didnt set i=0
Re: generating 10 unique random numbers in C
Quote:
Originally Posted by
superbonzo
after the first for loop the "i" variable equals 10, so the while loop never run.
By the way, if you had stepped through your code with the debugger you'd have seen it immediately.
yeah i did and i found out...it was super-lame of me to even ask...:(
Re: generating 10 unique random numbers in C
Quote:
Originally Posted by
creeping death
yeah i did and i found out...it was super-lame of me to even ask...:(
Note random_shuffle in the C++ standard.
Re: generating 10 unique random numbers in C
Code:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i=0,j=0,n=0,a[10],flag=1;
for(i=0;i<10;i++)
{
a[i]=-1;
}
i = 0;
srand(time(NULL));
while(i<10)
{
n=rand()%10;
flag = 1;
for(j=0;j<10;j++)
{
if(n==a[j])
{
flag=0;
break;
}
}
if(flag==1)
{
a[i]=n;
i++;
}
}
for(i=0;i<10;i++)
{
printf("%d\n",a[i]);
}
}
Re: generating 10 unique random numbers in C
You'll probably want to call srand in there too.