Programming in C

(Barry) #1
The whileStatement 59

Program 5.7 Output


Please type in two nonnegative integers.
150 35
Their greatest common divisor is 5


Program 5.7 Output (Rerun)


Please type in two nonnegative integers.
1026 405
Their greatest common divisor is 27


The double %icharacters in the scanfcall indicate that two integer values are to be
entered from the keyboard.The first value that is entered is stored in the integer variable
u, whereas the second value is stored in the variable v.When the values are actually
entered from the terminal, they can be separated from each other by one or more blank
spaces or by a carriage return.
After the values have been entered from the keyboard and stored in the variables u
and v, the program enters a whileloop to calculate their greatest common divisor. After
the whileloop is exited, the value of u, which represents the gcdof vand the original
val ue of u, is displayed at the terminal, together with an appropriate message.
Program 5.8 illustrates another use of the whilestatement, the task of reversing the
digits of an integer that is entered from the terminal. For example, if the user types in
the number 1234, you want the program to reverse the digits of this number and display
the result of 4321.
To write such a program, you first must come up with an algorithm that accomplish-
es the stated task. Frequently, an analysis of your own method for solving the problem
leads to the development of an algorithm.To reverse the digits of a number, the method
of solution can be simply stated as “successively read the digits of the number from right
to left.”You can have a computer program “successively read” the digits of the number
by developing a procedure to successively isolate or “extract” each digit of the number,
beginning with the rightmost digit.The extracted digit can be subsequently displayed at
the terminal as the next digit of the reversed number.
You can extract the rightmost digit from an integer number by taking the remainder
of the integer after it is divided by 10. For example, 1234 % 10 gives the value 4, which
is the rightmost digit of 1234, and is also the first digit of the reversed number.
(Remember the modulus operator, which gives the remainder of one integer divided by
another.) You can get the next digit of the number by using the same process if you first
divide the number by 10, bearing in mind the way integer division works.Thus, 1234 /
10 gives a result of 123, and 123 % 10 gives us 3, which is the next digit of your
reversed number.
This procedure can be continued until the last digit has been extracted. In the general
case, you know that the last digit of the number has been extracted when the result of
the last integer division by 10 is 0.

Free download pdf