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

happens, execution continues with the statement, if any, after <statement>. If <condition> is

false the first time, <statement> is not executed and execution continues with the following

statement, if any.

In Program P5.1, <condition> is num != 0 and <statement> is the block

{

}

sum = sum + num;

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

scanf("%d", &num);

Whenever we want to execute several statements if <condition> is true, we must enclose the

statements by { and }. Effectively, this makes them into one statement, a compound statement,

satisfying C’s syntax rule that requires one statement as the body.

5.2.1 Highest Common Factor

Let us write a program to find the highest common factor, HCF (also called the greatest common

divisor, GCD), of two numbers. The program will run as follows:

Enter two numbers: 42 24

Their HCF is 6

We will use Euclid’s algorithm for finding the HCF of two integers, m and n. The algorithm is as

follows:

1. if n is 0, the HCF is m and stop

2. set r to the remainder when m is divided by n

3. set m to n

4. set n to r

5. go to step 1

Using m as 42 and n as 24, step through the algorithm and verify that it gives the correct

answer, 6.

Steps 2, 3, and 4 are executed as long as n is not 0. Hence, this algorithm can be expressed

using a while loop as follows:

while n is not 0 do

set r to m % n

set m to n

set n to r

endwhile

HCF is m

96

www.it-ebooks.info

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

Saved successfully!

Ooh no, something went wrong!