the loop executes the ...statements...
as long as condition / is true
...statements... is the "body"
not(condition) is the "termination condition"
since the condition is at the end, a do while loop
always executes the "body" at least one time
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
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] %