Docsity

Repetition and Loop Statements: GCD of Two Numbers and Weather Report, Cheat Sheet of Career Counseling

Partial preview of the text

Download Repetition and Loop Statements: GCD of Two Numbers and Weather Report and more Cheat Sheet Career Counseling in PDF only on Docsity!

Repetition and Loop Statements

GCD of Two Numbers

The greatest common divisor (GCD) of two

integers is the product of the integers’

common factors. Write a program that inputs

two numbers and find their GCD by repeated

division. For example, consider the numbers

252 and 735. find the remainder of one

divided by the other.

GCD problem

Input Output Logic Involved

Two numbers GCD of the

numbers

Euclidean algorithm,

binary GCD algorithm,

repeated division

method

Algorithm to Find GCD

Step 1: Read the numbers from the user

Step 2: Let dividend = number1 and divisor =

number

Step 3: Repeat step 4 to step 6 while remainder not

equal to zero

Step 4: remainder = number1 modulus number

Step 5: dividend = divisor

Step 6: divisor = remainder

Step 7: GCD = divisor

Step 8: print GCD

Weather problem

Input Output Logic Involved

Rainfall in cm

recorded for ten

days, ten

numbers

Number of

days low,

medium

and high

rainfall

Count the number of

days with rainfall as

low, medium and high

Algorithm for Weather Problem

Step 1: Let counter =0, num_Of_Low = 0, num_Of_Med =

0, num_Of_High = 0

Step 2: If counter == 10 then goto Step 9

Step 3: Read rainfall recorded in cm

Step 4: increment counter

Step 5: if rainfall < 12 then increment num_Of_Low

Step 6: if rainfall is between 12 and 20 then increment

num_Of_Med

Step 7:Step 5: if rainfall > 20 then increment num_Of_High

Step 8: Goto Step 2

Step 9: Print num_Of_Low, num_Of_Med, num_Of_High

Used when we can determine prior to loop

execution exactly how many loop repetitions will be

needed to solve the problem

A counter-controlled loop follows this general

format:

Set loop control variable to an initial value of 0

while (loop control variable < final value)...

Increase loop control variable by 1

Counter-controlled loop

GCD Program Using While

Weather Program Using While

Weather Program Using For