first proper tutorial, be kind. =P
Cases, as far as I know can only go from an integer, so we are going to start by declaring said integer. =D
#include <stdio.h>
main()
{
int age;
We will call the integer age, because it's a number that can vary and you can give relevant different responses too so it makes it ideal.
We now want a printf, and a scanf to ask them to enter their age.
printf("Please enter your age\n");
scanf("%d", age);
Now our code has a main, an int, a printf and a scanf, it's time for our switch! ^_^. I'll put it into the whole code so it is easily understandable.
#include <stdio.h>
main()
{
int age;
printf("Please enter your age\n");
scanf("%d", age);
switch (age)
{
case 1:
printf("Congratulations on your first birthday\n");
break;
case 16:
printf("You can now legally have sex\n");
break;
case 18:
printf("You can now vote!\n");
break;
case 21:
printf("You are now twenty-one, enjoy the good years!\n");
break;
default:
printf("We don't care about your age!\n");
break;
}
fflush(stdin);
getchar();
}
the switch (age) is a fancy if statement, doesn't declare anything. each case is if that number is entered in the age variable.
default statement: The default statement is if it doesn't match any of the above cases, do this. ^^ Like a final else after an if.
We use breaks to make the code know to stop and that it's the end of that segment so it does not keep going through each case.
it then prints out each option, and breaks.
as a side note:
Cases are easier to read than a whole group of if else statements.
Cases are faster, especially if the program you are writing is huge.
Hope this helps somebody. :)
Edit: thanks to Jordan for his suggestion!
Edited by Phoenixz, 17 January 2009 - 09:44 AM.


Sign In
Create Account



Back to top










