Today's article is going to be about switch statements which are a lot like else if
statements.
So before diving into that, let's get the definition of what a switch is.
The switch statement evaluates an expression, matching the expression's value against a series of case clauses, and executes statements after the first case clause with a matching value, until a break statement is encountered.
ππππ
I bet you didn't understand that right?
Don't worry. I got confused the first few times of reading this. But what it really means is that a switch statement allows a variable to be tested for equality against a list of values.
That's all it basically means. Just like in the code below, let's assume it's a program to tell a user congratulations for entering the number 5. So the way we would normally do this is like thisπ
#include<stdio.h>
int main(void) {
int number = 0;
printf("Enter a number between 1 and 10: ");
scanf("%d",&number);
if(number == 5){
printf("Congratulations\n");
} else {
printf("Try again\n");
}
return 0;
}
See, if you were to run this program and enter 5, could you guess the output?
Yes, you guessed it right. It's going to print Congratulations
. Now let's do the same thing using the switch statements below.
#include<stdio.h>
int main(void) {
int number = 0;
printf("Enter any number between 1 and 10: ");
scanf("%d",&number);
switch(number) {
case 5:
printf("Congratulations");
break;
default:
printf("Try again");
break;
}
return 0;
}
switch(number)
in general terms is written as switch(expression or value)
. This means that it takes the value entered by the user and compares it with various cases, and when it lands on a case that is true, in our case, this is case 5:
, so it runs the lines of code within case 5:
and break
statements.
Now you may have noticed, that I used just one case which is case 5:
but you can add as many cases as you want, always try to remember that cases are just like the if-else-if ladder.
The image below represents the switch statement in a simple way. This was made by the Design Archive.
And as an exercise to you, I would recommend you draw out the flowchart for this code and send it to me at tifukelison@gmail.com.
And this will be all for this episode of the switch statements guys.
Until next time.
Peace.