Search code examples
csrand

Simple C Program Error..Can't resolve it


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


Solution

  • 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.