Reputation: 13
I'm trying to generate random numbers in C using srand(). I want to generate numbers from 1 to 25 without duplication, So i have implemented the following program.
#include <stdio.h>
#include <time.h>
int main()
{
int i=0,n,a[25]={0},b[25]={0},cntr=0;
srand(time(NULL));
while(cntr!=25)
{
n=rand()%26;
if(n!=9)
{
if(a[n]!=1)
{
a[n]=1;
printf("%d ",n);
b[i]=n;
printf("%d\n",b[i]);
cntr++;
i++;
}
}
}
for(i=0;i<25;i++)
{
printf("%d ",b[i]);
}
return 0;
}
Now there is a weird problem. When i print the array b inside the loop where the random number is generated it prints correct numbers. But when i print it outside the loop the first element of the array b changes to 1 and i get duplicate value of 1 in the random numbers. I would appreciate if anyone can help to find error in the program.
Here is the link to ideone where i have provided the output of the program : Ideone Link
Upvotes: 0
Views: 206
Reputation: 16540
there are several little oops in the posted code.
the following corrects those oops
#include <stdio.h>
#include <stdlib.h> // srand(), rand()
#include <time.h> // time()
int main()
{
int i=0; // generated number counter
int n; // generated number
int a[25]={0}; // tracks which numbers have been generated
int b[25]={0}; // random array of numbers 1...25
srand(time(NULL));
while(i<25) // correct loop termination
{
n=rand()%25+1; // yields 0...24 +1 gives 1...25
if(a[n]!=1)
{ // then, number not previously generated
a[n]=1; // indicate number generated
printf("%d ",n); // echo number
// save number in current location in array 'b'
b[i]=n;
printf("%d\n",b[i]); // echo number again
i++; // step offset into array 'b' (and loop counter)
} // end if
} // end while
for(i=0;i<25;i++)
{
printf("%d ",b[i]);
} // end for
return 0;
} // end function: main
Upvotes: 1
Reputation: 1
You declare a[25]
but you access any of 26 elements since n=rand()%26;
, so declare instead
int i=0,n,a[26]={0},b[26]={0},cntr=0;
BTW, compile with all warnings and debug info (e.g. gcc -Wall -Wextra -g
). Then use the debugger (gdb
). A watchpoint would have helped.
Upvotes: 2