I am trying to write a c++ program to print a random 10 letter string from a-z (ascii code 97 to 122) with non-repetitive letters. I have written this code which sometimes runs perfectly but most of the times the while loop runs infinitely. Where's the problem?
(EDIT: setting flag=0 at the beginning of while fixes the problem)
void randomstring() {int i,j,flag=1; char x, s[20]=" "; srand(time(0)); for(i=0;i<10;i++) {flag=1; //ensure entry into while while(flag) {x=rand()%26+97; //get random letter from a-z for(j=0;j<10;j++) {if(x==s[j]) //match with existing letters flag=2; //if matched, try again } if(flag!=2) {s[i]=x; //if doesn't match, add to string flag=0; //exit while } } } cout<<s; }