HPlogo HP C/HP-UX Reference Manual: Version A.05.55.02 > Chapter 6 Statements

do...while

» 

Technical documentation

Complete book in PDF

 » Table of Contents

 » Index

Syntax

do
      statement;
while (expression);

Arguments

statement

A null statement, simple statement, or compound statement.

exp

Any expression.

Description

The do statement executes statements within a loop until a specified condition is satisfied. This is one of the three looping constructions in C. Unlike the for and while loops, do...while performs statement first and then tests expression. If expression evaluates to nonzero (true), statement executes again, but when expression evaluates to zero (false), execution of the loop stops. This type of loop is always executed at least once.

You can jump out of a do...while loop prematurely (that is, before expression becomes false) by doing the following:

  • Use break to transfer control to the first statement following the do...while loop.

  • Use goto to transfer control to some labeled statement outside of the loop.

  • Use a return statement.

Example

/* Program name is "do.while_example". This program finds the
* summation (that is, n*(n+1)/2) of an integer that a user
* supplies and the summation of the squares of that integer.
* The use of the do/while means that the code inside the loop
* is always executed at least once.
*/
#include <stdio.h>
int main(void)
{
int num, sum, square_sum;
char answer;

printf("\n");
do
{
printf("Enter an integer: ");
scanf("%d", &num);
sum = (num*(num+1))/2;
square_sum = (num*(num+1)*(2*num+1))/6;
printf("The summation of %d is: %d\n", num, sum);
printf("The summation of its squares is: %d\n",
square_sum);
printf("\nAgain? ");
fflush(stdin);
scanf("%c", &answer);
} while ((answer != 'n') && (answer != 'N'));
}

If you execute this program, you get the following output:

Enter an integer: 10
The summation of 10 is: 55
The summation of its squares is: 385

Again? y
Enter an integer: 25
The summation of 25 is: 325
The summation of its squares is: 5525

Again? n

© Hewlett-Packard Development Company, L.P.