Hi
Just needed to post a couple of exercises im struggling on from Learn C the Hard Way - exercise 13: Exercise 13: Switch Statement
The "extra credit" Im not sure about is:
- Use the ',' (comma) to initialise letter in the for-loop. &
- Make it handle all of the arguments you pass it with yet another for-loop.
The code I've come up with is below I hope its readable....
I can understand how to make it handle a second argument but not an indefinite amount. I also can't understand how to initialise Letter in the for-loop using comma.
If theres somebody who doesnt mind explaining this to me I would very much appreciate it.
Thanks very much
Code:
#include <stdio.h>
int main(int argc, char *argv[])
{
if(argc < 2) {
printf("ERROR: You need one argument.\n"); // this is how you abort a program
return 1;
}
int i = 0;
for(i = 0; argv[1][i] != '\0'; i++) {
char letter = argv[1][i];
switch(letter) {
case 'a':
case 'A':
printf("%d: 'A'\n", i);
break;
case 'e':
case 'E':
printf("%d: 'E'\n", i);
break;
case 'i':
case 'I':
printf("%d: 'I'\n", i);
break;
case 'o':
case 'O':
printf("%d: 'O'\n", i);
break;
case 'u':
case 'U':
printf("%d: 'U'\n", i);
break;
case 'y':
case 'Y':
if(i > 2) {
// it's only sometimes Y
printf("%d: 'Y'\n", i);
}
break;
default:
printf("%d: %c is not a vowel\n", i, letter);
}
}
if(argc >= 2) {
for(i = 0; argv[2][i] != '\0'; i++) {
char letter = argv[2][i];
switch(letter) {
case 'a':
case 'A':
printf("%d: 'A'\n", i);
break;
case 'e':
case 'E':
printf("%d: 'E'\n", i);
break;
case 'i':
case 'I':
printf("%d: 'I'\n", i);
break;
case 'o':
case 'O':
printf("%d: 'O'\n", i);
break;
case 'u':
case 'U':
printf("%d: 'U'\n", i);
break;
case 'y':
case 'Y':
if(i > 2) {
// it's only sometimes Y
printf("%d: 'Y'\n", i);
}
break;
default:
printf("%d: %c is not a vowel\n", i, letter);
}
}
}
return 0;
}