You are on page 1of 26

MIS 131

Introduction to Algorithms and


Programming

2020/2021 Fall

- Chapter 1 –

Algorithms, Pseudocodes and Flowcharts

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Objectives
• In this chapter, you will learn:
– Basic problem solving techniques.
– Inputs and outputs of a problem
– Concept of variables
– To be able to develop algorithms through the process of top-down,
stepwise refinement
– To be able to convert the algorithm to pseudocode and flowcharts

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

2.1 Introduction
• Before writing a program:
– Have a thorough understanding of the problem
– Carefully plan an approach for solving it
– The program should be carefully designed
• While writing a program:
– Know what “building blocks” are available
– Use good programming principles

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

1
4

2.2 Algorithms
• Computing problems
– All can be solved by executing a series of actions in a
specific order
• Algorithm: procedure in terms of
– Actions to be executed
– The order in which these actions are to be executed
• Program control
– Specify order in which statements are to be executed

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Deck of Cards
• In a game - deck of cards
• Each player pulls a card at the top of the deck
• Read the task written on it
• Perform the task
• Then pull the next card on the top of the deck

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Example 2.1 Registration


• A real life example
• Describe steps of registration to a university
• Step by step description of how a newcomer can
register to a university

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

2
7
Example 2.1. Registering to an University
Algorithm

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Notice that
• When each step is compleated
– next step is passed
• It is also possible to branch a previous or later step
– in this example from step 6 to srep 2
• The action in each step may depend on a condition
– in step 6 if everything is OK continue otherwise branch to
step 2
• Each of these steps may consists of sub steps
– ex: step 2 fill out forms: there may be three different forms
– each of which may be a sub step of step 2
• 2a : a from for registration office
• 2b : a form for university hospital
• 2c : a form for university library
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Example 2.2 Calculating area of a regtangle


• Calcuating area of a rectangle
• Algortihm:

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

3
10

Note
• Without performing steps 2 and 3
• Step 4 can not be performed
• Similarly
• Without performing steps 4
• Step 5 can not be performed
• But
• Steps 2 and 3 can be interchanged

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

11

Exercis 2.1
• Pick up a real life situation that interests you
• For example:
– driving a car
– cooking egg or cake
• Construct the algorithm to explain step by step
description of the actions to someone who does
not have any idea about that situation

2 minutes!

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

12

2.3 Pseudocode
• Pseudocode
– Artificial, informal language that helps us develop programs
– One step closer to programming languages
– Similar to everyday English on one side and programming
languages on the other side
– Not actually executed on computers
– Helps us “think out” a program before writing it
• Easy to convert into a corresponding C/Java program
• Consists only of executable statements

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

4
13

Pseudocode for Example 2.2


1 Start
2 a Display “Enter height of the rectange”
2 b Input heigth
3 a Display “Enter width of the rectange”
3 b Input width
4 Set area = height * width
5 Display “The area of the regtanle” , area
6 Stop or end

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

14

Note That
• In the algorithm: in step 2
– Getting the height from the user
• In the pseudocode
– first write a message to be displayed in the screen informing
the user what to enter as an input
– Then let the user enter a real number and press ENTER key
– The number entered by the user is stored in the variable
heigth
• Similarly for getting width of the rectangle – in
step 3

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

15

Note That (Cont.)


• When the pseudocode is implemented in any
programming language such as Java, C# or Python
• The user first sees the message
“Enter height of the rectange ”
in the computers screen
The user is expected to enter real number for the height end
press ENTER key
• The Input heigth statement
– Obtains the characters entered by the user
– Converts into a numerical variable named height to be
used in subsequent steps of the pseudocode or program

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

5
16

Building Blocks
• Input output transfer
• Calculations in between - processing
• Decision making
• Iteration
• Variables
– Store data in memory
– Different types in different languages
– Integers, real, character, string, logical,...
• Input: obtain a value from the user and store in a variable
– Enter a value for radius of a circle to compute its area
– Enter your name lastname id number
– Make a choice Yes/No to save or not

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

17

Variables
– Store data in memory
– Different types in different languages
– Integers, real, character, string, logical (true or false) ...
• Integer: Holds whole numbers (i.e., 3, 25, 1000, etc.)
• Real: Holds either whole numbers or numbers with a fractional
part (i.e., 3.5, 0.4, 1000.01, etc.)
• String: Holds any string of characters (i.e., someone’s name,
address, etc.)
• Numerical variables
– heigth, width, age, totalSales, numer of children
• Strings:
– Name, last name, address, e-mail
– “Nazım”, “Taşkın”, “abc@boun.edu.tr”
– usually presented in quats “.....”
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

18

Variable in Daily Life


• What is your name?
– stored in your memory as a string
• What is your age or weight
– you know the meaning of age or weight
– stroded as an integer or real and changes over time
• What is your GPA
– you know what GPA is but not yet has a value as a new
student
• What is your garbay score
– this does not make a sense to you
– no such think in your memory
– when asked you are supprised or hesitate to answer
– BUT A COMPUTER PROGRAM FAILS
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

6
19

Output
• Output: Display the results of the problem
– Some variables
• display area
– Constant messages
• Display “welcome to Java”
• Display “you failed to register”
– Expressions
• Display pi*r2
– or a mixture of them
• Display “the area is:”, area
– E.g.: displays when the value of area is 200
– the area is: 200

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

20

Calculations - Processing
• Calculations
• Aritmetic and logical computations
• Intermediate results are also in variables
• E.g.:
– Set area = height*width
• area is the product of hight and width
– E.g.:
• Set valueAddedTax = taxRate*basePayment
– E.g.:
– Set total = total + new grade
• add new grade to the total

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

21

2.4 Control Structures


• Sequential execution
– Statements executed one after the other in the order written
• Transfer of control
– When the next statement executed is not the next one in
sequence
– Overuse of goto statements led to many problems
• Bohm and Jacopini
– All programs written in terms of 3 control structures
• Sequence structures: Built into Java. Programs executed
sequentially by default
• Selection structures: Java has three types: if, if…else, and
switch
• Repetition structures: Java has three types: while, do…while
and for
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

7
22

Simple Building Blocks


• We will start with
– Input
IPO
• Get data from the user
• Store in variables
– Process or calculation
• Store the results in (new) variables
– Output
• Display message and/or variables to the screen
• Variables of different types
– Stored in memory
– Referen by a name in our pseudocodes, and programs

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

23

2.5 Flowcharts
• Flowchart
– Graphical representation of an algorithm
– Drawn using certain special-purpose symbols connected by
arrows called flowlines
– Rectangle symbol (action symbol):
• Indicates any type of action
– Oval symbol:
• Indicates the beginning or end of a program or a section of code
• Single-entry/single-exit control structures
– Connect exit point of one control structure to entry point of
the next (control-structure stacking)
– Makes programs easy to build

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

24

Flowchart Symbols

start or end
calculation

flow

decision making

output input

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

8
25

Example 2.3 Foreign Exchange Problem


• The amount of $ in your hand makes how much TL
• $1 = 7.90 TL
• Inputs:
– Amount of dollar in your hand
• Output:
– How much does the dollar worth in terms of TL
• Limitations
– 1 is 7.90 TL forex rate is constant
– Just convert to TL

Same question with a different view – Next slide

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

26

Foreign Exchange Problem – Another View


• Question: What input do I need to perform this
algorithm?
– Answer: I need dollar amount
– I need exchange rate (given/constant in this example)

• Question: What must I do with the input?


– Answer: I must multiply the dollar amount with the
exchange rate. The result of that will give me how much TL
the entered dollar amount equals to

• Question: What output must I produce?


– Answer: TL amount
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

27

Ex 2.3 Algorithm of exchange rate


calculation

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

9
28

Pseudocode

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

29

Variables
• forexRate
– a real number set at the begining
– fixed; it does not change
• dollar
– dollar in the hand of the user
– real input
– every run of the program has a different value
• tl
– calculated TL amout for the dollar with the fixed forexRate

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

30

Limitations and Extensions


• Limitations:
– Every time a new $ is given the algorithme start from begining
– If the user enters a negative value it prints a negative TL
– If the user enters a character it fails to compute
• Note:
– Should the exchange rate be asked as a second input or is it
fixed as it is not chaning very often but it may change hourly?
– Exercise:
• Modify the algorithm when the forexRate change as well
1 Start
2a Display "Enter exchange rate: " Space?
2b Input forexRate
3a Display “Enter dollar in your hand:”
3b Input dollar
4 Set tl = dollar * forexRate
• Extension of the problem 5 Display “your”, dollar , “worths”, tl
6 Stop or End
– Given TL the user may want to chose the forex ohter then dollar
to purchase
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

10
31

Ex 2.4. Length Conversion


• What is the equivanent of a given inch in term of cm
• Inputs:
– inch
• Output:
– cm
• Limitations:
– just between inch and cm
• Note: relation between cm and inch is constant and
– 1 inch is 2.54 cm

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

32

Ex 2.5. Area and Circunference of Circle


• Given a radius of a circle calcualte its area and
Input Processing Output
circunference Radius Multiply the radius of the circle Area
with the square of Pi (3.14) to
• Inputs: calculate the area of the circle. Circumference

– Radius Multiply the radius of the circle


with 2 times Pi (3.14) to
• Output: calculate the circumference of
the circle.
– Area and circumference
• Note has two outputs
• Limitations:
– Only for circle
• Note: Pi is a universal constant as well 3.14159

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

33

Area and Circumference of Circle


• 1 Start
• 2 Set the value of pi = 3.1416
• 2 Get radius
• 4 Compute area and circunference
• 4.a area = pi * (radius)2
• 4b circunf. = 2 * pi * radius
• 5 Display area and circunference to the screen
• 6 Stop or end

• What are variables?


– radius, area, circunference
• What about pi?
– its value does not change – universal constant
• What are the limitations of the algorithm?

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

11
34

Pseudocode for Cirlcle

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

35

Ex 2.7 Display a Fixed Message


• Display your signiture to the screen
• When run always displays your name, last name,
address and e-mail to the screen
• Limitation: only one signature for you
• No input, no variables
• Output
Name: Nazım
Last name: Taşkın
Address: Bogazici University
E-mail: abc@boun.edu.tr
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

36

Ex 2.8 Asking and Displaying your Personal


Information
• Task: ask name lastname and age
• dispay to the screeen
• Inputs : name, lastName – String
• age - integer
• Output: A messge that change according to your
name last name and age but has some fixed
characters
• Example output
Name: BB
Last Name: Taşkın
Age: 6
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

12
37

Algorithm
• 1 Start
• 2 Ask and get name, last name and age of a person
• 2a Ask and get name
• 2b Ask and get last name
• 2c Ask and get age
• 3 Dispay personal information in a formated way
to the screen
• 3a Display name
• 3b Display last name
• 3c Display age
• 4 Stop
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

38

Pseudocode
• 1 Start
• 2a i Display “Enter your name”
• 2a ii Input name
• 2b i Display “Enter your last name”
• 2b ii Input lastName
• 2c i Display “Enter your age”
• 2c ii Input age
• 3a Display “Name: ” , name
• 3b Display “Last Name:”, lastName
• 3c Display “Age:”, age
• 4 Stop
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

39

Variables
• name, lastName
– String – set of characters
• age
– integer - your age

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

13
40

Flowchart
• Draw the flowchart

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

41

Ex 2.9. Exam grades


• Computes exam statistics
• Inputs:
– student grades

• Outputs:
– avgerage, min, max, letter grades, ...
• Limits:
– only for one exam

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

A Simple Grade Average Calculation


Problem
• Task: There are only three students in a class
• Ali, Ahmet and Nazlı. Get their exam grades from
the user and calculate and display the class
average to the screen.

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

14
43

Algorithm
• A class consisting of three students: Ali,Ahmet, Nazlı
1 Start
2 Get Ali’s grade
3 Get Ahmet’s grade
4 Get Nazlı’s grade
5 Compute the average grade
Average grade = (Ali’s grade + Ahmet’s grade + Nazlı’s
grade)/3
6 Display the average grade
7 End

• Variables:
– Ali’s grade, Ahmet’s grade, Nazlı’s grade,
– average grade

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Pseudocode and Variables


1 Start
2a Declare Integer alisGrade
2b Declare Integer ahmetsGrade
2c Declare Integer nazlisGrade
2d Declare Real average
3a Display “Enter Ali’s grade”
3b Input alisGrade
4a Display “Enter Ahmet’s grade”
4b Input ahmetsGrade
5a Display “Enter Nazli’s grade”
5b Input nazlisGrade
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Pseudocode and Variables (cont.)


6 Set average = (alisGrade + ahmetsGrade +
nazlisGrade)/3
7 Display “the class average” , average
8 End

Variables
alisGrade, ahmetsGrede and nazlisGrade are declared as
integers
average is declared as Real
Note that: if this pseudocode is implemented in Java or C
programming languages sum of three integers is an
integer dividing by 3; you may lose the remainder
because of integer division
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

15
Solution
• Declare the student grades as Real variables
average = (10.0 + 9.0 + 9.0) / 3
here average is 9.33333
• if grades are declared as integers
average = (10 + 9 + 9) / 3
here average is 9.00000

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

Another Important Feature


• In step 6 of the pseudocode
• Average can be computed in one assignment
statement
• or it can be computed is steps as follows
6a Set sum = alisGrade
6b Set sum = sum + ahmetsGrade
6c Set sum = sum + nazlisGrade
6d average = sum / 3
How do you get rid of the information lose due to
integer division ?
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

48

Ex 2.10. Purchase
• What is total payment after a sale?
• Inputs:
– products SKU (Stock Keeping Unit) and amounts
• Outut:
– invoice total payment with value added tax
• Note prices of goods are not inputs

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

16
49

Purchase Problem Task


• Two products Apple and Pair
– prices are given not changing
• Value added tax
– tax rate is constant
• Input:
– AmoutApple, AmountPair – asked to user
• Output:
– netPay, VAT, grossPay – calculated and printed
• Variables:
– PriceApple, PricePair – fixed
– AmoutApple, AmountPair – asked to user
– VAT Rate – fixed
– netPay, VAT, grossPay – calculated and printed
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

50

Purchase Problem Algorithm


• 1 Start
• 2a Define prices for the two goods
– PriceApple = 4, PricePair = 5
• 2b Define value added tax rate
– VATRate = 0.18
• 3 Get amount of apple and pair purchased from the user
• 4 Calculate net payment
– netPay = PriceApple*AmountApple + PricePair*AmountPair
• 5 Calculate VAT
– VAT ? netPay*VATRate
• 6 Calculate gross payment
– grossPay = netPay + VAT
• 7 Print net payment, VATand total payment to screen
• 8 End
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

51

Pseudocode Flowchart
• Exercise to you
• Note if you are sure that value of a variable will
not change through out the program, you can
declare them a constant.
• Many programming languages including Java has
a syntax for constants
• Any attempt to change the value of a constant is a
syntax error
• Examples of well known constants
pi = 3.1416, e = 2.713
speed of light, Avagadro number
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

17
Constants in Pseudocodes
• Constant Integer priceApple = 4
• Constant Real Pi = 3.14

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

53

Notes Purchase Problem


• Note that
• Calculating net Payment can be performed in two
steps as:
– 4a Set netPay = PriceApple*AmountApple
– 4b Set netPay = netPay + PricePair*AmountPair

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

54

Ex 2.11.Tax Calculation
• Compute the tax burden
• Inputs:
– yearly income

• Output:
– tax burden
• Note: tax rate is given

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

18
55

Ex. 2.12 Interest Calculation


• Depositing some money calculate interest earned on that
• Inputs:
– Principle
– term
– yearly interest rate
• Output:
– money
– interest earned

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

56

Exercise
• Suppose a language does not support mode
• In Java mode is implemented by %
– 14 % 3 = 2
– 12 % 3 = 0
• How do you imlement mode if it is not supported
by the language syntax

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

57

Solution

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

19
Ex 2.13 ATM Problem
• Consider a customer intending to withdraw money from an
ATM, enters the amount s/he wants to withdrow
• available types of notes are say:
– 100, 50, 20, 10...
– assume ATM pays as much 100 as possible then pays the
remaining with 50s and so on
• Write the algorithm of money withdrawing problem. How
much of the money is paid with what type of notes and
remainging money that can not be paid at all
• E.g.: 643 TL is paid with
– 6x100s, 0x50s, 2x20s, and 3 TL can not be paid

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

ATM Problem Hint


• Hint: at each step try to identify how much of the
money is paid with say by 100s and what is the
remaining amount

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

60

ATM Input and outputs


• Input:
– money from the user
• Output:
– how many 100 TL
– how many 50 TL
– how many 20 TL
– how much not paid

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

20
61

ATM: Algorithm

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

62

Pseudocode of Step 3a and 3b

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

63

Exercise
• Complete the pseudocode
• Draw the flowchart
• -- Write the Java program

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

21
64

Exercise Time Expression 1


• Given a duration of time in hours, munites and
seconds, express it in total seconds
• E.g.:
given 2 hours, 3 minutes and 5 seconds
it is 7385 seconds

given 2 hours, 0 munites and 30 seconds


it is 7230 seconds

given 0 hours, 20 munites and 40 seconds


it is 1240 seconds
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

65

Exercise: Time Expresion 2


Given a duration of time in seconds, express it in
hours, minutes and seconds
E.g.:
given 7385 seconds
it is: 2 hours, 3 minutes and 5 seconds

given 7230 seconds


it is 2 hours, 0 munites and 30 seconds

given 1240 seconds


it is 0 hours, 20 munites and 40 seconds
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

66

Exercise: Exchange of values of variables


• Given two int type variables
• a, b holding values
• E.g.: a = 5, b = 10
• Change their values
• At the end of the change
• a becomes 10 , b becomes 5
• i) By using a temporary variable
• ii) Without using a temporary variable

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

22
67

Exercise: Reverse of an Integer


• Given a three digit integer
– Examples: 174, 810, 400, 956
• Print it in reverse order
– Examples 174 to 471, 956 to 659, 400 to 4, 810 to 18
• Hint: Try to get its first digit, second digit and
third digit
• Then try to construct the reverse number

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

68

Input and output


• Input:
– a three digit integer from the user
• Output:
– its reverse

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

69

Algorithm 1

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

23
70

Variables for Algorithm 1


• Variables
– number– input from user
– reverse – output to screen
– ones, tens, hundreds, remaining

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

71

Hearth of the Algorithm 1


• Set remaining = number // take a copy of number
• 3 determine ones:
3a Set ones = remaining mode 10
3b Set remaining = remaining / 10

• Example:
– number is 743
– remaining is 743
– ones is 743 mode 10 = 3
– remaining is 743 / 10 74
• perform step 4 amd 5 to find tens and hudereds
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

72

Algorithm 2
• 1 Start
• 2 Get number from user
• 3 Determine hundrends
• 4 Determine tens
• 5 Determine ones
• 6 Compute reverse as
– invnumber = 100*hundreds+10*tens+ones
• 7 Display reverse
• 8 End

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

24
73

Algorithm 2
• Set remaining = number // copy of money
• 3 Determine hundreds:
3a Set hundreds = remaining / 100
3b Set remaining = remaining mode 100
• Example:
– number is 743
– remaing is 743
– hundreds is 743 / 100 = 7
– remaining is 743 mode 100 = 43
• Perform step 4 and 5 to find tens and ones

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

74

Algorithm 3
• 1 Start
• 2 Initialize reverse to zero
• 3 Get number from user
• 4a Determine ones
• 4b Update remainder
• 4c Update reverse
• 5a Determine tens
• 5b Update remainder
• 5c Update reverse

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

75

Algorithm 3 (contg.)
• 6a Determine hundrends
• 6b Update remainder
• 6c Update reverse
• 7 Print reverse
• 8 End

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

25
76

Hearth of Algorithm 3
• Initially reverse variable is set to 0
• 4a Determine ones:
• Set ones = remaining mode 10
• 4b update remainder
• Set remaining = remaining / 10
• 4c updata reverse
• Set reverse = 10*reverse + ones // inverse
becomes ones

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

77

Hearth of Algorithm 3
• Just before 5 inverse is ones
• 5a determine tens:
• Set tens = remaining mode 10
• 5b update remainder
• Set remaining = remaining / 10
• 5c updata reverse
• Set reverse = 10*reverse + tems // inverse
becomes left digit:onces, right digit: tens

© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved.

26

You might also like