I've been trying to execute the following code.. However, I keep getting the same errors over and over again and I don't know why!
My code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void){
int randomNum;
char takenWords[4];
char words[20]={"DOG", "CAT", "ELEPHANT", "CROCODILE", "HIPPOPOTAMUS", "TORTOISE", "TIGER", "FISH", "SEAGULL", "SEAL", "MONKEY", "KANGAROO", "ZEBRA", "GIRAFFE", "RABBIT", "HORSE", "PENGUIN", "BEAR", "SQUIRREL", "HAMSTER"};
srand(time(NULL));
for(int i=0; i<4; i++){
do{
randomNum = (rand()%20);
takenWords[i]=words[randomNum];
}while((strcmp(&words[randomNum], takenWords) == 0)&&((strcmp(&words[randomNum], &takenWords[i])==0)));
printf("%s\n", &words[randomNum]);
}
getchar();
return 0;
}
I have counted the number of elements which I entered in the array and they do not exceed 20!
Also, why do I keep getting the 'Implicit conversion loses integer precision error'?
I guess you want to make arrays of pointers instead of arrays of characters.
Try this:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
int main(void){
int randomNum;
const char *takenWords[4];
const char *words[20]={"DOG", "CAT", "ELEPHANT", "CROCODILE", "HIPPOPOTAMUS", "TORTOISE", "TIGER", "FISH", "SEAGULL", "SEAL", "MONKEY", "KANGAROO", "ZEBRA", "GIRAFFE", "RABBIT", "HORSE", "PENGUIN", "BEAR", "SQUIRREL", "HAMSTER"};
srand(time(NULL));
for(int i=0; i<4; i++){
int dupe=0;
do{
randomNum = (rand()%20);
takenWords[i]=words[randomNum];
dupe=0;
for(int j=0;j<i;j++){
if(strcmp(words[randomNum],takenWords[j])==0)dupe=1;
}
}while(dupe);
printf("%s\n", words[randomNum]);
}
getchar();
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With