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.3

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

#include <stdio.h>

int main() {

int num, sum = 0, n = 0;

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

scanf("%d", &num);

while (num != 0) {

n = n + 1;

sum = sum + num;

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

scanf("%d", &num);

}

printf("\n%d numbers were entered\n", n);

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

}

The following is a sample run of the program:

Enter a number (0 to end): 24

Enter a number (0 to end): 13

Enter a number (0 to end): 55

Enter a number (0 to end): 32

Enter a number (0 to end): 19

Enter a number (0 to end): 0

5 numbers were entered

The sum is 143

Comments on Program P5.3

• We declare and initialize n and sum to 0 before the while loop.

• The statement

n = n + 1;

adds 1 to n. We say n is incremented by 1. Suppose n has the value 3.

• When the right-hand side is evaluated, the value obtained is 3 + 1 = 4.

This value is stored in the variable on the left-hand side, that is, n. The net

result is that 4 is stored in n.

• This statement is placed inside the loop so that n is incremented each time

the loop body is executed. Since the loop body is executed when num is not 0,

the value of n is always the amount of numbers entered so far.

98

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!