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

We can now write Program P5.2, which finds the HCF of two numbers entered.

Program P5.2

//find the HCF of two numbers entered by a user

#include <stdio.h>

int main() {

int m, n, r;

printf("Enter two numbers: ");

scanf("%d %d", &m, &n);

while (n != 0) {

r = m % n;

m = n;

n = r;

}

printf("\nTheir HCF is %d\n", m);

}

Note that the while condition is n != 0 and the while body is the block

{

}

r = m % n;

m = n;

n = r;

The algorithm and, hence, the program, works whether m is bigger than n or not. Using the

example above, if m is 24 and n is 42, when the loop is executed the first time, it will set m to 42 and

n to 24. In general, if m is smaller than n, the first thing the algorithm does is swap their values.

5.3 Keep a Count

Program P5.1 finds the sum of a set of numbers entered. Suppose we want to count how many

numbers were entered, not counting the end-of-data 0. We could use an integer variable n to hold

the count. To get the program to keep a count, we need to do the following:

• Choose a variable to hold the count; we choose n.

• Initialize n to 0.

• Add 1 to n in the appropriate place. Here, we need to add 1 to n each time

the user enters a nonzero number.

• Print the count.

Program P5.3 is the modified program for counting the numbers.

97

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!