08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 5 ■ Programs with Repetition Logic

Program P5.1

//print the sum of several numbers entered by a user

#include <stdio.h>

int main() {

int num, sum = 0;

printf("Enter a number (0 to end): ");

scanf("%d", &num);

while (num != 0) {

sum = sum + num;

printf("Enter a number (0 to end): ");

scanf("%d", &num);

}

printf("\nThe sum is %d\n", sum);

}

Of particular interest is the while statement. The pseudocode

while num is not 0 do

add num to sum

get another number, num

endwhile

is expressed in C as

while (num != 0) {

sum = sum + num;

printf("Enter a number (0 to end): ");

scanf("%d", &num);

}

When the program is run, what would happen if the very first number entered was 0? Since

num is 0, the while condition is immediately false so we drop out of the while loop and continue

with the printf statement. The program will print the correct answer:

The sum is 0

In general, if the while condition is false the first time it is tested, the body is not executed

at all.

Formally, the while construct in C is defined as follows:

while (<condition>) <statement>

The word while and the brackets are required. You must supply <condition> and

<statement>. <statement> must be a single statement or a block—one or more statements

enclosed by { and }. First, <condition> is tested; if true, <statement> is executed and

<condition> is tested again. This is repeated until <condition> becomes false; when this

95

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!