Ok, I need to make a program that randomly generates 4 random letters from 12 random letter and it cannot reapeat the same letter. for example you can only pick from a,b,c,d,e,f,g,h,i,j,k,l and the program can randomly generate a,b,c,d or b,c,d,e but should not generate a,a,b,b or something that repeats.Another is that a letter represents 1 animal. I'm new to rand() and srand() so any links on rand() srand() tutorial may help too. :)

#include<stdio.h>
#include<stdlib.h>
int main()
{
    char a=ant,b=bear,c=cat,d=dog,
    e=emu,g=goat,l=lizard,m=monkey,
    p=parrot,r=rabbit,s=snake,t=tiger;
    int i;
        for(i=1,i<=4,i++)
        {printf("%c %c %c %c",&i &i &i &i);
        system("pause");
        return 0;
        }

so far I made these but I don't know how and where to add rand and srand()and it ca't be compiled as well. I'm not sure if the a=ant thing is correct as well.

Recommended Answers

All 5 Replies

documentation
The char a = ant; is only valid if ant is a character defined at some other location (unlikely in your code example). A char variable can only hold values of a single character ( 'a', 'b', 'c' for example). In your case it might be better to investigate enumerations ( enum ) as it will allow a name to be associated to an integer value as you seem to want:

enum animal { ANT = 0, BEAR, CAT, DOG, ... };

If you wanna store the names like a = ant you should use strings (char*).

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

#define sz 12

int main()
{
	int i, j;
	char* animals[sz] = {"ant", "bear", "cat", "dog", "emu", "goat", "lizard", "monkey", "parrot", "rabbit", "snake", "tiger"};
	char* chosen[4] = {"", "", "", ""};
	srand(time(NULL));

	for( i = 0; i < 4; i++ )
	{
		chosen[i] = animals[rand()%12];
		for( j = 0; j < 4; j++ )
			if( strcmp(chosen[i], chosen[j]) == 0 && j != i ) //checks to see if the animal picked is unique
			{
				i--; //if not decrease counter so it overwrites the last animal
				break;
			}
	}

	for( i = 0; i < 4; i++ )
	{
		printf("%c - ", chosen[i][0]); //for first letter of animals name
		printf("%s  ", chosen[i]); //for whole name of animal
	}
	printf("\n");


	return 0;
}
commented: Very informative :) +0

Thanks a lot! :) I'm new on C programming just studied about If-Else and Switch and for and I read about some rand() and srand() but I don't seem to get it.Can you suggest any links that might teach those codes you just written cause I want to learn to make programs like those too. Anyways I really really appreciate your help! :)

THANKS A LOT~! :) the link helped me a lot :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.