Switch Statements

Image compliments of java-forums.org.

Switch statements are replacements for if, else statements. It allows for ciphering through data. They are very good for finding specific characters within an array that a user inputs. Let’s see an example!

#include <stdio.h>

#include <stdlib.h>

int main(){

char arrayname [0]; //array name length 0. 0 counts as an integer value of length 1

puts(“enter a character A-C”);//this does the same thing as printf but only works for text

scanf(“%s”, arrayname);//reads in user data

switch(arrayname[0]){ //switch name and position

case ‘A’://gives conditions

case ‘a’://don’t forget to account for capital and lowercase characters they are not the same
puts(“you chose A”);//prints to console, "you chose A"

break;/*break means that the condition was true and it exits the loop. */

case ‘B’:
case ‘b’:
puts(“you chose B”);
case ‘C’:
case ‘c’:
puts(“you chose C”);
default://default accounts for all invalid inputs
puts(“you didn’t pick A-C);}
return 0}


So when placed into your compiler you can see how the switch statement reduces your need for writing a billion if else statements. You could also do this in if else statements by doing if (A) else if (a) else if (B) else if (b)… Do not forget to place a break; without it it continues through the switch to the next case.

Note: You can switch through an array that is dependent on a variable. i.e. 
switch(arrayname [i]){

In the loop when you define cases make sure to add a counter variable (i++).
This allows to check the cases for every character in the array.


Tip: Make sure you put in breaks!! This is the biggest mistake I see when working with switch statements.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s