Jump to content United States-English
HP.com Home Products and Services Support and Drivers Solutions How to Buy
» Contact HP
More options
HP.com home
HP C/HP-UX Reference Manual: HP-UX Systems > Chapter 6 Statements

while

» 

Technical documentation

Complete book in PDF
» Feedback
Content starts here

 » Table of Contents

 » Index

Syntax

while ( exp )
        statement

Arguments

exp

Any expression.

statement

This statement is executed when the while (exp) is true.

Description

The while statement executes the statements within a loop as long as the specified condition, exp, is true. This is one of the three looping constructions available in C. Like the for loop, the while statement tests exp and if it is true (nonzero), statement is executed. Once exp becomes false (0), execution of the loop stops. Since exp could be false the first time it is tested, statement may not be performed even once.

The following describes two ways to jump out of a while loop prematurely (that is, before exp becomes false):

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

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

Example

/* Program name is "while_example" */
#include <stdio.h>

int main(void)
{
int count = 0, count2 = 0;
char a_string[80], *ptr_to_a_string = a_string;

printf("Enter a string -- ");
gets(a_string);

while (*ptr_to_a_string++)
count++; /* A simple statement loop */
printf("The string contains %d characters.\n", count);
printf("The first word of the string is ");

while (a_string[count2] != ' ' && a_string[count2] != '\0')
{
/* A compound statement loop */
printf ("%c", a_string[count2]);
count2++;
}
printf("\n");
}

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

Enter a string Four score and seven years ago
The string contains 30 characters.
The first word of the string is Four

Printable version
Privacy statement Using this site means you accept its terms Feedback to webmaster
© Hewlett-Packard Development Company, L.P.