C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
printf("Return of the King\n");
printf("2004: Million Dollar Baby\n");
printf("2005: Crash\n");
printf("2006: The Departed\n");
printf("2007: No Country for Old Men\n");
printf("2008: Slumdog Millionaire\n");
printf("2009: The Hurt Locker\n");
printf("\n\n\n");
break;
} else if (choice2 == 3)
{
printf("\n\nUS Presidents in the 2000s:\n");
printf("2000: Bill Clinton\n");
printf("2001-2008: George Bush\n");
printf("2009: Barrack Obama\n");
printf("\n\n\n");
break;
} else if (choice2 == 4)
{
exit(1);
} else
{
printf("Sorry, that is not a valid choice!\n");
break;
}
}
case (4):
exit (1);
default: printf("\n%d is not a valid choice.\n",
choice1);
printf("Try again.\n");
break;
}
} while ((choice1 < 1) || (choice1 > 4));
return 0;
}

Now, this might look intimidating at first glance, but consider a few things. First of all, you are more
than halfway through this book, so have a little faith in your C knowledge. Second, long does not mean
hard—just break down the code section by section, and you’ll find nothing too intimidating in this
code.


This program has two levels of menus to it. At the top menu, you are asking the user to select a
specific decade: the 1980s, the 1990s, or the 2000s. After the user picks 1 , 2 , or 3 for the chosen
decade (or 4 to quit the program), a switch statement sends the program to the next level of menus.
The user then gets information about sports (specifically baseball), the movies, or U.S. presidents.
Within each case section of code, if and else statements test the user’s entry to present the
information they want to see.


You might be thinking, “Hey, the switch statement was a great idea for the top menu—why not use
it for the next level of menu choices as well?” Well, although you can nest if statements in other if

Free download pdf