UMBC CS 201, Fall 98
Control Structures
Sequential structures
Statements will be executed in the order they're written.
Selection structures
Single-selection structure
The if structure is a single-selection
structure because it selects or ignores a single action.
Double-selection structure
The if/else structure is called
a double-selection structure, because it selects between two different
actions.
Multiple-selection structure
The switch structure is called a
multiple-selection structure, because it selects one of many possible
actions. (to be discussed later)
Repetition structures
- The while loop has a condition that
is tested before the loop is entered. The loop will continue to execute as
long as that condition is true.
- The do/while loop always executes once,
since the condition is given at the end of the loop. The loop will execute
again if the condition is true. (to be discussed later)
- The for loop executes a specified number
of times.
(to be discussed later)
if
The if structure
if ( condition )
{
statement(s)
}
Example :
/* make sure x is positive */
if (x < 0)
{
x = -x;
}
The if/else structure
if ( condition )
{
statement(s)
}
else
{
statement(s)
}
Example :
/*assign a grade */
if (score >= 70)
{
grade = 'P';
}
else
{
grade = 'F';
}
while
The while loop
while (condition)
{
...statements...
}
- not(condition) is the "termination condition"
- ...statements... is the "body"
Example problem
Write a program to add a list of numbers entered
at the keyboard. The end of the input is
indicated by entering 0 as a sentinel value.
Program
/*
* File: addlist.c
* Author: Sue Bogar
* Date: 2/2/98
* ---------------
* This program adds a list of numbers. The end of
* the input is indicated by entering 0 as a
* sentinel value. A priming read is necessary to
* gain entry into the loop.
*/
#include
main()
{
int value, total;
/* Give directions to user */
printf("This program adds a list of numbers.\n");
printf("Signal end of list with a 0.\n");
/* Initialize total */
total = 0;
/* Get the first integer from the user
This is known as a "priming read" */
printf("Enter an integer, 0 to end : ");
scanf("%d", &value);
/* Continue to get integers from the user
until a 0 is entered, accumulating into total */
while (value != 0)
{
total = total + value;
printf("Enter an integer, 0 to end : ");
scanf("%d", &value);
}
/* Print the total */
printf("The total is %d\n", total);
}
Output
lassie% cc addlist.c
lassie%
lassie% a.out
This program adds a list of numbers.
Signal end of list with a 0.
Enter an integer, 0 to end : 1
Enter an integer, 0 to end : 2
Enter an integer, 0 to end : 3
Enter an integer, 0 to end : 4
Enter an integer, 0 to end : 5
Enter an integer, 0 to end : 6
Enter an integer, 0 to end : 7
Enter an integer, 0 to end : 8
Enter an integer, 0 to end : 9
Enter an integer, 0 to end : 10
Enter an integer, 0 to end : 0
The total is 55
lassie%
CSEE
|
201
|
201 F'98
|
lectures
|
news
|
help
Monday, 07-Sep-1998 15:01:43 EDT