UMBC CS 201, Fall 07
UMBC CMSC 201
Fall '07

CSEE | 201 | 201 F'07 | lectures | news | help

The C do while loop


    do
    {
        ...statements...
    }while (condition);

Example problem

Write a program to add a list of integers entered at the keyboard. The end of the input is indicated by entering 0 as a sentinel value.

Program

/***************************************** * File: dowhile.c * Author: D. Frey * Date: Fall 1999 * Section: 0101 * E-Mail: frey@cs.umbc.edu * * This program adds a list of integers. The end of the * input is indicated by entering 0 as a sentinel value. * * This implementation uses a do while loop. *****************************************/ #include <stdio.h> int 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 integers from the user until ** a 0 is entered */ do { printf("Enter an integer, 0 to end : "); scanf ("%d", &value); total += value; }while (value != 0); /* Print the total */ printf("The total is %d\n", total); return 0; }

Output

linux1[96] % 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 linux1[97] %


CSEE | 201 | 201 F'07 | lectures | news | help

Thursday, 23-Aug-2007 12:00:52 EDT