Practical C Programming – Switch and Nested Switches Example

Print Friendly, PDF & Email

I wanted to explore a further level of switching to implement a sub level menu within a main switch option, by adding to my Imperial to metric units converter. This allows extra functionality to a handy program – a two way units conversion choice.  

Although trial and error placement is slow, it does let you think more about a program's operation, so help the learning curve, rather than just google an answer. The first working version program code is:

 

unitconverter.png

This offers only metric to Imperial units conversion at present:

$ ./unitsconverter
program to convert Imperial units to metric. Enter menu option:
1: km to miles
2: litres to pints
3: kg to pounds
q: quit
1
1: convert km to miles. Enter km value: 1
1.000000 km is 0.621 miles

program to convert Imperial units to metric. Enter menu option:
1: km to miles
2: litres to pints
3: kg to pounds
q: quit
w
Invalid key, try again! w

program to convert Imperial units to metric. Enter menu option:
1: km to miles
2: litres to pints
3: kg to pounds
q: quit
q

Now it was just finding the correct format using clues from the above switch cases – with breaks in the right places – to make the extra nested switch options behave as desired. The first working case 1 sub menu code is shown below so you can see how it enters the first case option and breaks out to the main menu after either choice is completed:

 

This shows both extra options working as required:

$ ./unitsconverter2
program to convert Imperial units to metric. Enter menu option:
1: km to miles
2: litres to pints
3: kg to pounds
q: quit
1
Want to (k) convert km to miles or (m) miles to km?: k
k: convert km to miles. Enter km value: 1
1.000000 km is 0.621 miles

program to convert Imperial units to metric. Enter menu option:
1: km to miles
2: litres to pints
3: kg to pounds
q: quit
1
Want to (k) convert km to miles or (m) miles to km?: m
m: convert miles to km. Enter miles value: 1
1.000000 m is 1.609 km

program to convert Imperial units to metric. Enter menu option:
1: km to miles
2: litres to pints
3: kg to pounds
q: quit
Invalid key, try again! w

program to convert Imperial units to metric. Enter menu option:
1: km to miles
2: litres to pints
3: kg to pounds
q: quit
q

unitsconv2.c.png

Now it's just a case of pasting the same format to the other 2 options and re-arranging the formulae and units.

The exit beaks from the final main case 3 have to be correctly placed with {}'s to account for the default already in place:

case3conv.png