# Thread: Explanation of switch statements

1. ## Explanation of switch statements

Hello-

I have to write a program that converts numbers into words. I know I have to use switch statements for this but I dont really understand the switch statement to begin with and how it workds and in turn I dont understand how I would use them for this program. Could someone help with an explanation? I dont want a program wirrten- just how switch statements work- and how i would use them with this program. Thanks!!

Jenna

2. It's like an if statement. Post your coding attempt at it, and advise will follow.

3. ## ?

can i use if statements for this instead of switch statements? I understand if statements and I would rather use them if I can. I was told switch statements would be easier. Thanks.

Jenna

4. If it helps, post your attempt using an if...else tree, and perhaps then we can show a switch equivalent.

Or better yet -- post your "easy" if...else version, and then your attempt at converting it to a switch equivalent.

5. Code:
```if(apple==2){
printf("Wow, there's two apples");
}
else if(apple==3{
printf("Three apples! Yay!");
}
else if(apple==4){
printf("So many apples!");
}
else{
printf("Apple...");
}```
equals to:
Code:
```switch(apple){
case 2:
printf("Wow, there's two apples");
break;
case 3:
printf("Three apples! Yay!");
break;
case 4:
printf("So many apples!");
break;
default:
printf("Apple...");
break;
}```

6. ## Thank you!

Thank you for your code example. I can see the relation now! Thanks!!!

7. Originally Posted by ammochck21
Hello-

I have to write a program that converts numbers into words. I know I have to use switch statements for this but I dont really understand the switch statement to begin with and how it workds and in turn I dont understand how I would use them for this program. Could someone help with an explanation? I dont want a program wirrten- just how switch statements work- and how i would use them with this program. Thanks!!

Jenna
A switch statement is often not the only option. If the numbers you are using are all consecutive then you can use a simple array lookup.
This works especially well if you use enums for your item types.
Code:
```enum fruitType {APPLE, BANANA, CHERRY};
const std::string fruitName[] = {"Apple", "Banana", "Cherry"};

fruitType f = BANANA;
cout << fruitName[static_cast<int>f];```
Easy as ABC.