im trying to print the array 5 times, each time containing different numbers but it repeats the same random numbers. help please.

while(count<5){
                       fillarr2(ran1,ran2);
                      printar(ran1,ran2,counting);
}

// functions

void fillarr2(int raa[],int rab[]){
     int ran1,ran2, i,count=0;
     srand(time(NULL));
     
     
     for(i=0;i<10;i++){
                       ran1=rand()%15+1;            
                       raa[i]=ran1;
                       } 
      
      for(i=0;i<10;i++){
                        ran2=rand()%15+1;
                        rab[i]=ran2;
                        
                        }
                                                      
return ;
}  

void printar(int x1[],int x2[],int cc){
     int i,ran,ran2;
     cout<<" 1st array holds ";
    outfile<<" 1st array holds ";
     for(i=0;i<cc;i++){
                       cout<<x1[i]<<"  ";
                       outfile<<x1[i]<<"  ";
                       }
                       cout<<endl;
                       outfile<<endl;
     cout<<" 2nd array holds ";
     outfile<<" 2nd array holds ";
     for(i=0;i<cc;i++){
                      cout<<x2[i]<<"  ";
                      outfile<<x2[i]<<"  ";
                      }
                      cout<<endl;
                      cout<<endl;
                      outfile<<endl;
                      outfile<<endl;
    
     
     return;
     }

everytime it runs in the main the same random numbers are displayed, the generator works but only once.

Edited 5 Years Ago by Narue: Added code tags

Very few RNGs actually produce truly random values. The numbers are actually the result of a mathematical formula that produces a random-looking sequence of numbers. The seed tells the RNG where to start in the sequence.

Your code probably works every time, but because the code executes so fast the seed never changes. Since the seed never changes, the RNG starts at the same spot in the sequence each time so it simply doesn't look like it's working when it actually may be.

You should only seed the RNG once in your entire program. Move the seed out of your fillarr2() function and put it at the very beginning of your main().

Edited 5 Years Ago by Fbody: n/a

This article has been dead for over six months. Start a new discussion instead.