i write a C code to generate a random character and check if this character exists in an array if it exist i want to re-generate a new char . i'm used a fag as an indicator and used do{}while() loop to check this flag , but unfortunately code doesn't work as desired and i get a numbers already exist in the array : (
i need your help to understand and solve the problem .
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
char c ;
int num ;
int flag = -1 ;
char temp[5] = { '3' , '2' , '5' ,'9' , '1' } ;
srand(time(NULL)) ;
do{
num = rand()%5 ;
c = num ;
for( int i = 0 ; i<5 ; i++)
{
if(temp[i] == c )
{
flag = 0 ;
break ;
}
else
{
flag = 1 ;
}
}
}while(0==flag);
printf("number is : %d\n" , c ) ;
return 0 ;
}
Aucun commentaire:
Enregistrer un commentaire