08.01.2023 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5 ■ Programs with Repetition Logic

Like before, we get the first number before we enter the while loop. This is to ensure that the

while condition makes sense (is defined) the first time. It would not make sense if num had no

value. If it is not 0, we enter the loop. Inside the loop, we process the number (compare it with

bigNum, etc.) after which we get another number. This number is then used in the next test of the

while condition. When the while condition is false (num is 0), the program continues with the

print statement after the loop.

This algorithm is implemented as shown in Program P5.4.

Program P5.4

//find the largest of a set of numbers entered

#include <stdio.h>

int main() {

int num, bigNum = 0;

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

scanf("%d", &num);

while (num != 0) {

if (num > bigNum) bigNum = num; //is this number bigger?

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

scanf("%d", &num);

}

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

}

Let us “step through” this program using the sample data entered at the beginning of this

section. For easy reference, the data was entered in the following order:

36 17 43 52 50 0

Initially, num is undefined and bigNum is 0. We show this as:

num bignum 0

36 is entered and stored in num;

num is not 0 so we enter the while loop;

num (36) is compared with bigNum (0);

36 is bigger so bigNum is set to 36, giving:

num 36 bignum 36

103

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!