UMBC CS 201, Fall 98
UMBC CMSC 201 & 201H Fall '98 CSEE | 201 | 201 F'98 | lectures | news | help

Control Structures

Sequential structures

Statements will be executed in the order they're written.

Selection structures

Repetition structures


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...
    }

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 <stdio.h> 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