C Statements - The Case Statement
(Page 4 of 4 )
As you can see from the above code, working with a boatload of If, Else and Else...Ifs can get not only time-consuming, but hard to read as well. To simplify matters, we can use the Case statement instead. Here is the same program as above, with the same results:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int rhyme;
printf("Enter a number from 0-5: ");
scanf_s("%i",&rhyme);
switch(rhyme)
{
case '1':
printf("n One...a big fat bun.");
break;
case '2':
printf("n Two...I hate you");
break;
case '3':
printf("n Three...You look like Mr. T");
break;
case '4':
printf("n Four...Don't vote for Al Gore");
break;
case '5':
printf("n Five...Quit talking Jive");
break;
case '0':
printf("n Zero...You know I'm yer hero");
break;
default:
printf("nThat number is not between 0-5 you dummy.");
}
return(0);
}
A lot better. It's easier to use, and saves the programmer a lot of coding.
We will cover the Case statement more in the Loops tutorial, which should poke its head around the corner in another article or two.
Wrapping It Up
You may have noticed that we focused on numeric values in all of our statements in this article. This was by design. Dealing with text is a little more complex in C than one would hope, as though some irate number-loving hippie accountant had created it. But never fear; we will cover this very topic in our next exciting episode. And hopefully we will discuss the basics of Logical Operators in Statements, Nesting Statements, and Loops, though that too may have to wait for a few more issues as well.
So stick around, because there is a lot of learning to do and let's face it: you need all the knowledge you can get.
Till then...
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |