Reputation: 69
#include <stdio.h>
int main(void)
{
char ch;
//character = ch
printf("Please type a character [A-Z or a-z] ('x'to exit):");
scanf("%c", &ch);
switch(ch) //switch statement
{
case 'a':
printf("%c is a vowel.\n", ch);
break;
case 'e':
printf("%c is a vowel.\n", ch);
break;
case 'i':
printf("%c is a vowel.\n", ch);
break;
case 'o':
printf("%c is a vowel.\n", ch);
break;
case 'u':
printf("%c is a vowel.\n", ch);
break;
case 'A':
printf("%c is a vowel.\n", ch);
break;
case 'E':
printf("%c is a vowel.\n", ch);
break;
case 'I':
printf("%c is a vowel.\n", ch);
break;
case 'O':
printf("%c is a vowel.\n", ch);
break;
case 'U':
printf("%c is a vowel.\n", ch);
break;
default:
if(ch != 'x'){
printf("%c is a consonant.\n", ch);
break; }
else if(ch == 'x'){
printf("%c is a consonant.\n", ch);
break; }
}
I have been having much trouble with this code. I have it perfect however it needs to keep repeating until 'x' is entered. Tried a while loop, couldn't have any luck, just recently tried the if statement in the default, that doesnt work either. I'm so close if anyone could give me a little insight!
Upvotes: 1
Views: 3508
Reputation: 224844
You don't need to repeat yourself so much. You can use multiple labels for a given case:
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
printf("%c is a vowel.\n", ch);
break;
default:
printf("%c is a consonant.\n", ch);
break;
You do need a loop:
do
{
printf(...)
scanf(...)
switch (...)
{
...
}
} while (ch != 'x');
You might want to add an isalpha
call in there before doing the switch
at all.
Upvotes: 7
Reputation: 2363
while(ch != 'x'){
...
...
}
or maybe you can do a function menu approach
void runMenu(){
// do stuff
runMenu();
}
I would look at @Carl Norum's answer for code optimization!
Upvotes: 0