-
January 28th, 2009, 06:03 AM
#1
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
-
January 28th, 2009, 06:12 AM
#2
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.
-
January 28th, 2009, 06:16 AM
#3
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
-
January 28th, 2009, 06:18 AM
#4
Re: generating 10 unique random numbers in C
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...
-
January 28th, 2009, 07:16 AM
#5
Re: generating 10 unique random numbers in C
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.
-
January 28th, 2009, 07:19 AM
#6
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]);
}
}
Last edited by xk82180316; January 28th, 2009 at 07:22 AM.
-
January 28th, 2009, 08:23 AM
#7
Re: generating 10 unique random numbers in C
You'll probably want to call srand in there too.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|