Sams Teach Yourself C in 21 Days

(singke) #1
Basic Program Control 141

6


1 - Add a Record
2 - Change a record
3 - Delete a record
4 - Quit
Enter a selection: 4
You chose Menu Option 4
This program provides a menu with four choices. You can select one of the four
choices. The program then prints the number selected. Programs later in this
book use and expand on this concept. For now, you should be able to follow most of the
listing. The main()function (lines 7 through 16) adds nothing to what you already know.

ANALYSIS

The body of main()could have been written into one line, like this:
printf( “You chose Menu Option %d”, get_menu_option() );
If you were to expand this program and act on the selection, you would
need the value returned by get_menu_choice(), so it is wise to assign the
value to a variable (such as choice).

Note


Lines 18 through 37 contain get_menu_choice(). This function displays a menu on-
screen (lines 24 through 30) and then gets a selection. Because you have to display a
menu at least once to get an answer, it is appropriate to use a do...whileloop. In the
case of this program, the menu is displayed until a valid choice is entered. Line 34 con-
tains the whilepart of the do...whilestatement and validates the value of the selection,
appropriately named selection. If the value entered is not between 1 and 4 , the menu is
redisplayed, and the user is prompted for a new value. When a valid selection is entered,
the program continues to line 36, which returns the value in the variable selection.

Thedo...whileStatement
do
{
statement(s)
}while (condition);
conditionis any valid C expression, usually a relational expression. When condition
evaluates to false (zero), the whilestatement terminates, and execution passes to the first
statement following the whilestatement; otherwise, the program loops back to the do,
and the C statement(s) in statement(s)is executed.
statement(s)is either a single C statement or a block of statements that are executed
the first time through the loop and then as long as conditionremains true.

,


S

YNTAX

,


10 448201x-CH06 8/13/02 11:20 AM Page 141

Free download pdf