-
Need help with "Switch"
Ok, I was given an assignment that looks like this:
In a menu, ask the user whether they want to calculate the factorial of a non-negative number, or exit. If they choose to calculate the factorial and enter any negative number, print an error message and take them back to the main menu. If they choose an invalid menu option, print an error message and re-print the menu.
I'm completely new to switch and I have no idea what I'm doing wrong. What happens with the program is when I compile it gives me five lines of messages saying "Warning: Character constant too long for its type" on line 9. So I'm not sure whats going on there. But when I run it the menu shows up with option 1 and 2 but when I type a number and press enter nothing happens. Any suggestions?
Code:
#include <stdio.h>
int main () {
int j,i,k,result,num;
num = 5;
while (num == 5) {
printf("Please choose a menu item:\n1. Factorial\n2. Exit\n");
scanf("%d\n", &k);
switch (k) {
case 'k == 1':
printf("Enter a number:\n");
scanf("%d\n", &i);
result = 1;
for (j=i;j>=1;j--)
result = result*j;
printf("%d! = %d\n",i,result);
break;
case 'k == 2':
return 0;
break;
case 'k > 2':
printf("Sorry - Invalid menu option, please select again.\n");
break;
case 'k < 1':
printf("Sorry - Invalid menu option, please select again.\n");
break;
}
}
}
-
You never did hit I'm feeling lucky on Google did you.
Case labels must be constant integral values, so you could have case 42: and case -117: and case 65535: and so on.
-
Your code seems ok, but i would suggest that you read a bit about the switch.
Code:
switch( <integer expression> )
{
case <integer constant expression>: <statements> break;
...
}
The field <integer constant expression> means a number or something that evaluates to a number like: 5+6*7 and MUST be evaluatable before the program is compiled. Therefore the error in your code is the 'case' statement because case 'k == 1' actually is a valid integer constant expression but with a few compiler warnings about multibyte character constants... etc.
-
Quote:
Code:
case 'k > 2':
printf("Sorry - Invalid menu option, please select again.\n");
break;
case 'k < 1':
printf("Sorry - Invalid menu option, please select again.\n");
break;
Also you want to do range check on user input? Use an if() statement. It will save you writting twice the same error message...
-
I think you desperately need to learn indenting too. It's very important to gasp this concept early on.