You are on page 1of 217

Introduction to Programming

Concepts & Logic

1 CS002
- Programs are simply solutions to problems.

- To create a program we have to learn how to


think in a different way, the way computers
think.

CS002
2
General Problem-Solving
Concepts
Chapter 1

3 CS002
1. Identify the problem
◦ What is the specific problem?
(This means you should determine what is that
you want to change).
◦ Clearly define the goal that you want to
achieve. (What are you trying to achieve?).
◦ Determine what are the inputs and
outputs.

4 CS002
2. Understand the problem
◦ Gathering data relative to the problems which
your solution can be achieved.
◦ Do not automatically discard any information.

5 CS002
3. List possible solutions to the problem
◦ Generate as many potential solutions as
possible.
◦ List the features for each possible solution.

6 CS002
4. Select the best way to solve the problem
from the list of alternative solutions.
◦ Establish criteria to help when choosing the
solution
◦ Select the best solution.

7 CS002
5. List instructions that enable you to solve
the problem using the selected solution
(Do Stage).
◦ Planning:
Create a numbered, step-by-step set of
instructions

8 CS002
6. Evaluate the solution(Review and Revise)..
◦ Test the solution
Are the results accurate?
Does the solution solve the original problem?
Does it satisfy the needs of the user?
Is it acceptable to the user?

9 CS002
Now let’s put problem-solving into
action!

10 CS002
Problem description Steps Outcome.
Eman is a doctor and she Identify the problem. Problem: wanting to get contact to the old friends.
isn’t in regular contact Goal: get contact to the old friends.
with her old friends. She is
getting caught up in the Understand the problem. Facts: Searching for e-mail, telephone, home
demands of work and address…etc.
family and she’s not list possible solutions to the
1. Schedule a time e.g. every Sat. to contact by
setting aside time problem writing emails letters. (Cheap - long time to
specifically for old friends. write a letter – no need to be at the same time
available).
2. Buy plan tickets to visit them.
(real contacts, costly, must
have free time to do it)
1. Using phone call to contact.(real contact,
acceptable costs, need short free time ).
Select the best solutions to Criteria: 1- Time.
the problem. 2-Cost.
3- Interactivity.
So, phoning would be the best.
List instructions (Do Stage) Start calling tomorrow at launch time.
Schedule every Sunday at 10 am for calling
Write notes to remember on mirror and…
Tell the friend in advance to be ready.
Evaluate the solution Had great conversation but set a timer when she’s
(Review and Revise). talking so that she will not spend more on the phone
bill.

11 CS002
Problem Steps Outcome.
description
Today is the final Identify the problem. Problem: Enrolling in a university & department
day for Abeer in Goal: Name university and department that she will
high school, she & this year.
her family Understand the problem. Facts:
gathered to decide Searching for Universities available.
which university Knowing her grades, hobbies, specialties
for here to attend. and Gender.
list possible solutions to the go local university.(speed, not have desired
problem section, monthly reward)
go a broad.(trip expenses, have desired section,
free enrolment, monthly reward)
go private university.( trip expenses very
expensive , school I prefer, enrolment is not free )
Select the best solutions to Criteria:
the problem. 1- enters high ranked university and
desired section.
2- Not expensive.
3- Free.
So, solution 2.
List instructions (Do Stage) 1. Send an enrol application to the university.
2. Wait for reply.
3. Pack your stuff, go to university.
4. Attend first day.
Evaluate the solution I felt lonely, grades were low.
(Review and Revise). So, must change solution(revaluate)
12 CS002
Algorithmic Solutions
Steps involved in following a set of instructions.
The solution will be the same each time the algorithm is
followed.
Most computers use algorithmic types of problems.
Heuristic Solutions
Solutions that can’t be reached by following a direct set of
steps.
Created based on knowledge and experience…and by trial and
error.
The results may not produce the same results each time
the algorithm is executed.
Artificial intelligence deals with heuristic types of
problems.

13 CS002
The instructions that will result in the best
solution.
The result may be:
More Efficient
Faster
More Understandable
More Maintainable
Reusable

14 CS002
The outcome of the program

May take any form:


Printout
Updated files
Output to monitor, speakers, etc.

15 CS002
The set of instructions that make up the
solution after they have been coded into a
particular computer language.

Although we won’t be actually


writing programs, at least not in any
specific language, this is what we
will be working toward throughout
this course!
16 CS002
summary
There are 6 steps in problem solving
There are two types of problem solutions :
algorithmic and heuristic.
Algorithmic solutions reached step by step
Heuristic solutions through trial and error

17 CS002
1

BEGINNING PROBLEM-SOLVING
CONCEPTS FOR THE COMPUTER

Chapter 2
3 Types of Problems that can be solved on
computers :
2

Computational
problems involving some kind of mathematical
processing
Logical
Problems involving relational or logical processing
Repetitive
Problems involving repeating a set of mathematical
and/or logical instructions.
Fundamental Concepts
3

The building blocks of equations and expressions


Constants
Variables
Operators
Functions
Expressions
equations
Constants
4

A value
a specific alphabetical and/or numeric value
Does not change during the processing of all the
instructions in a solution
Can be of any data type
Numeric, alphabetical or special symbols
Examples
3, 5, 10, “Sara”, “+”, “-”, “/”
Constants
5

In some programming languages, constants can be


named
Provides protection to the constant value and other
areas of the program.
Cannot be changed once given initial value
Example
SalesTaxRate = 6
Commission_Rate = 6
Note: no spaces within variable names
Variables
6

May change during processing


In many programming languages, variables are
called identifiers.
The variable name should be consistent with what the
value of the variable represents
A name is assigned to each variable used in a
solution.
The name references the memory area where the value is
stored.
Variables
7

The computer uses the name as a reference to help


it find that value in its memory .
May be of any data type
Examples
Age, LastName, Address, PayRate
Difference between name of a variable and
value of a variable
8

The rule for naming variable differ from language to


language .
there will be no character- length limitations for
variable .
The computer uses the variable name to find the
location; it uses the value found at the memory
location to do the processing.
Rules for Naming Variables
9

1- name variable according to what it represents


√ Hours for hours worked.
x H for hours worked (correct but not
recommended because it is not clear enough).

√ PayRate for rate of pay.


x P for rate of pay (correct but not
recommended because it is not clear enough).
Create as short a name as possible, but one that clearly
represents the variable.
2- Do not use spaces
√ HoursWorked for hours worked (correct).
x Hours Worked Incorrect because the space.

√ StudentName for student name (correct).


x Student Name Incorrect because the space.
3 - Start a variable name with a letter.
√ Hours for hours worked (correct).
x 2hours Incorrect because starting by number 2.

√ Student for student name (correct).


x 8Student Incorrect because starting by number 8
4- Do not use a dash ( or any other symbol that is used
as mathematical operator).

For example:
√ StudentName for student name (correct).
x Student-Name Incorrect because using a dash symbol.
13

4 - Be consistent when using upper-and lower case


characters.

HOURS is different variable name than Hours


For example:
Age and AGE are two variables (not the same variable).
5 - Exact variable name must be used in all places
where the data item is used .
For example:
If the data item hours worked has the variable name of Hours, Hours must
be used consistently.
√ Hours hours worked
x Hrs or HoursWorked (Incorrect, it is a new variable).
6 - Use the naming convention specified by the company
where you work. The naming convention is uppercase for the
first character in each of the words in the name, with no
spaces between words in the name.

Variable Names Constant Name


PayRate PI
Rate KCONATANT
HoursWorked MULTIPLIER
Amount
Tempreature
StudentName
Data type
16

Data
unorganized facts.
They go into the computer as input .
Information
The output of processing of input .
Is printed in the form of reports.
Processing Data – How a computer
Balances a Checkbook
17

Input Data Output


Data Processed Report
into Information

Checks
Deposits Calculates the Balance
Bank Charge Balance Sheet
Data Types
18

Data can come with different type :(Most common types)


Numeric
Character
Logical
Computer should know the data type of each
variable or constant .
Most languages include other data types
Date
User-defined
Numeric Types
19

Include all types of numbers.


The only data type that can be used in numeric
calculation.
Integers
3, 5, -5, 0, -1 and 32,767
Real numbers (floating point numbers)
Are whole numbers plus decimal parts (3.1459, -5745)
Scientific Notation
2.3E5 or 5.4E-3,
where E stands for the Power of 10
Can be Positive or Negative.
Numeric data are used for value ( salary , rate of pay)
Data Types & Data Sets
20

Each data type has a data set


A data set is the set of value that are allowed in a
particular data type.
Data Types & Data Sets
Data Type Data Set Examples
Numeric :Integer All whole numbers 3456
-43
Numeric :Real All real numbers (whole + 3456.78
decimal) 0.000123
Character (uses All letters, numbers, and “A”, “a”, “1”, “5”, “+”,
quotation marks) special symbols “%”

String (uses quotation Combinations of more than “Mulder”


marks) one character “Scully”
“123-45-6789”
Logical True or False True
False

21
Character Types
22

Alphanumeric data set


Consists of
all single-digit numbers,
letters, and
special characters available to the computer
contained within quotation marks
An upper case letter is considered a different
character from a lower case letter .
Table of ASCII Characters
23

Char Dec Char Dec


A 65 a 97

B 66 b 98

C 67 c 99

D 68 d 100

E 69 e 101

...... ...... ...... ......

…... …... …... …...


String Data Type
24

Made up of one or more characters.


Contained within quotation marks
Cannot be used within calculations
Items that would not have mathematical
computations performed on them should be
designed string data type .
some languages do not differentiate between
characters and strings .
Strings - Caution
25

“123” is not the same thing as 123


The first one is a string
The second one is a number
Becomes important when deciding when a piece of
data is a string or a number
Ex. Social Security Numbers
The first one contains 11 characters and is left aligned
whereas the second contains 9 numbers and is right aligned
Comparing Characters & Strings
26

The computer’s particular coding scheme (ASCII,


Unicode, or EBCDIC) converts the character to its
associated ordinal number
The computer gives each character a number.
The number representation is necessary because the
computer work only with numbers.
example:
A 65
a 97
Comparing Characters & Strings
27

Note: Uppercase letters have a smaller ordinal values than


lowercase letters
“A” = 65 whereas “a” = 97 (ASCII 8-bit)
Once converted, each character, one at a time, can
be compared.
Example:
Banana is larger than Apple because B has larger
number representing it than A

COP1006 McManus
Comparing Characters & Strings
28

Concatenation could be used to join a first name with


a last name or to join pieces of data together.

Characters and String data can be compared and


arranged in alphabetical order (as ascending order).
Concatenation
29

Joins character data or string data together with the


+ operator .
Example :
“James” + “ ” + “T.” + “ ” + “Kirk” = “James T. Kirk”
“100” + “3” = “1003” not “ 103 “
Logical (Boolean) Data Type
30

Consists of two value in the data set :


True and False
Some languages accept yes, T, and Y for true .
no, F, and N c for False .
Example :
Check someone’s credit record ; true means credit is ok.
False means it’s not ok.
For example, the variable Warm might be declared as a
logical data type to describe if temperature values are
warm or not.
Other Data Types
31

date data type and user defined data type

Date data type is a number for the date that is


the number of days from a certain date .

Is a numeric data type because you can perform


mathematical calculation on any date .
User-Defined Data Types
32

User-defined Data types


Defined by the user as a new data type
Example( kind of cars )
Car_Type
GMC
Ford
Toyota
End
Rules for Data Types
33

Programmer chooses the data type during the


programming process .
The data that define the value of a variable or a constant
will be one of three data type : numeric , character or
logical .
Data types can not be mixed, Once a constant or a
variable has been given a data type it cannot change.
All data to be used in calculations must be declared as a
numeric data type.
Rules for Data Types
34

Each data type uses a data set or domain


Numeric – uses the set of all base 10 numbers, the plus
sign(+), and the negative sign(-) .
Characters – all characters included in the computer.
Logical – the words “true” and “false”
Data Data Type
The price of item Numeric
4.25 Real
Account number String
Examples of Data “1234567”
Types Room numbers Numeric
112 Integer
Name of company String
“Apple Macintosh”
Check status Logical
Pass/Fail
True or False
Date Date or
12/3/2011 String
How the Computer Stores Data
36

Data Storage
Each variable name is given a memory location
Each memory location can hold one and only one
value at a time.
This memories are temporary storage, when a user
enters a new value the old one is destroyed

Example:
COP1006 McManus
Functions
37

Small sets of instructions that perform specific tasks


and return values.
FunctionName(data)
Are used as parts of instructions in a solution .
Two types:
Pre-defined
each language has a set of functions within it .
User-defined
Programmers write their own functions.
Functions
38

The name of function may vary from language to


language
Benefits
Reduces the amount of code that needs to be written,
thus reducing errors of repetition.
Function Parameters
39

the data which is listed as part of the function and


are called parameters .
In Sqrt(n), the n represents the parameter, in this case a
number
In Value(s), the s represents a string
Not all function need parameters
In Random , no data are needed
Parameter can be a constant , a variable , or an
expression
Function Types
40

1. Mathematical
Used in science and business , Calculate such things as
square root, absolute value
2. String
Manipulate string variable
3. Conversion
Convert data from one data type to another
4. Statistical
5. Utility
Important in business programming
Mathematical Functions
41

Function Form Example Result


Square Root Sqrt(n) Sqrt(4) 2
Absolute Abs(n) Abs(-3), Abs(3) 3
Rounding Round(n,n1) Round (3.7259,2) 3.73
Integer Integer(n) Integer(5.7269) 5
Random Random Random 0.239768
Sign of a number Sign(n) Sign(7.39) 1
String Functions
42

Function Form Example Result


Mid(S,3,2) where
Middle String Mid(s, n1, n2) S = "Thomas" "om"
Left(S,3) where S
Left String Left(s, n) = "Thomas" "Tho"
Right(S, 3) where
Right String Right(s, n) S = "Thomas" "mas"
Length(S) where S
Length String Length(s) = "Thomas" 6
Conversion Functions
43

Function Form Example Result


Valued Conversion Value(s) Value("-12.34") -12.34
String Conversion String(n) String(-12.34) "-12.34"

For example, since character string can not be used


in calculations, one of these functions would convert
a string value to a numeric value
Statistical Functions
44

Function Form Example Result


Average Average(list) Average(5, 3, 8, 6) 5.5
Maximum Max(list) Max(5, 3, 8, 6) 8
Minimum Min(list) Min(5, 3, 8, 6) 3
Summation Sum(list) Sum (5, 3, 8, 6) 22
Utility Functions
45 Functio Definition Exampl Result
n e
Date Returns the current date from the Date 09/15/08
system. The date may be in various
forms:
mm/dd/yy, day only, month only, year
only, or Julian calendar
Time Returns the current time from the Time 9:22:34
system. The time may be in various
forms:
hh:mm:ss, seconds from midnight, or
minutes from midnight
Error Returns control to the program when a
systems error occurs.
Operators
46

The data connectors within expressions and


equations.
thy tell the computer how to process the data .
They also tell the computer what type of the
processing( mathematical, logical, or …..) needs to
done.
The operand are the data that the operator
connect and processes ( constants or variable).
The data type of the operands of an operator must
be the same.
The resultant is the answer that results when the
operation is completed .
The data type of operands and the resultant
depends on the operator .
Ex : 5 + 7
Operator Types
48

1. Mathematical
The data types of operands and resultants of
mathematical operators are always numeric
+, -, *, /
\, Mod ( used in business )
^
functions
Two Special Math Operators
49

Integer Division (\)


If given a Floating Point number, the number is
rounded—first—before division occurs.

Modulo Division (Mod) or Modulus


The remainder part of the answer is returned.
Mathematical Operators

Operator Compute Operation Resultant


r Symbol
Addition + 3.0 + 5.2 8.2
Subtraction - 7.5 – 4.0 3.5
Multiplication * 8.0 * 5.0 40.0
Division / 9.0/4.0 2.25
Integer division \ 9\4 2
Modulo division MOD 9 MOD 4 1
Power ^ 3^2 9
Relational Operators
51

Relational operators

Perform comparisons
the use of relational operators is the only way for the
computer to make decisions .
The resultant of relational operation is logical data type .
The operand s can be numeric or character
Relational operatores

Operator Computer Operation Resultant


Symbol
Equal to = 5=7 False
Less than < 5<7 True
Greater than > 5>7 False
Less than or equal to <= 5<=7 True
Greater than or equal to >= 5>=7 False

Not <> 5<>7 True


Logical Operators
53

AND, OR, NOT


used to connect relational expressions .
a = b AND c < d
Perform operations on logical data.
They are defined by using Truth Tables…
Logical opeartores

Operator Compute Operation Resultant


r Symbol
Not NOT NOT True False
And AND True AND True True
Or OR True OR False True
The AND Operator
55

Significance: The only time the result is True is


if both A and B are True.

A B A AND B
True True True
True False False
False True False
False False False
The OR Operator
56

Significance: The only time the result is False is


if both A and B are False.

A B A OR B
True True True
True False True
False True True
False False False
The NOT Operator
57

Also called the “logical complement” or


“logical negation”
Significance: Whatever the value of A is, NOT A
will be the opposite.

A NOT A
True False
False True
Hierarchy of Operations
58

Data and Operators are combined to form


expressions and equations
To evaluate these in the proper order, a hierarchy of
operations, or Order of Precedence, is used.
The processing of the operands always starts with
”functions” then the innermost parentheses and
works outward, and processes from left to right

Note: Whenever you want to clarify an equation, use


the parentheses!
The Order of Precedence
59
Order of Operations Operand Data Type Resultant Data Type

( ) reorders the hierarchy; all operations are completed within the


parentheses using the same hierarchy
Power ^ Numeric Numeric
\, MOD Numeric Numeric
*, / Numeric Numeric
+, _ Numeric Numeric
=, <, >, < =, > =, < > Numeric or string or Logical
character
NOT Logical Logical
AND Logical Logical
OR Logical Logical
Example
60

Evaluate the following:


A = True, B = False, C = True, D = False
A or B or C and D and A and B and (not C) or (not D)
To do this, we create what’s called an Evaluation
Tree…
61

A or B or C and D and A and B and (not C) or (not D)

False
True
False
False
False
False
True
True
True
Expressions & Equations
62

Expressions
Process the data and the operands, through the use
of the operators
Does not store the resultant (answer)
Examples :
to find the number of square feet in a room :

Length * Width
Equations
63

Same as an expression, except the equation stores


the resultant (answer) in a memory location
“takes on the value of” not equals

Examples

Area = Length * Width

Often called Assignment Statements


Expressions Equations

A+B C= A + B
A and B are numeric. C ,A and B are numeric.
The resultant is numeric and is The resultant is stored in C .
not stored
A<B C=A<B
A and B are numeric , character, A and B are numeric , character,
or string. or string .
The resultant is logical and is The resultant is stored in C ;
not stored . C is logical.
A OR B C = A OR B
A and B are logical . C ,A and B are logical .
The resultant is logical and is The resultant is stored in C .
not stored
Example : evaluating a mathematical
expression .

5*(X+Y)–4*Y/(Z+6)
uses the following values to evaluate the expression :
X=2 Y=3 Z=6
Operation resultant
1. X + Y 5
2. Z + 6 12
3. 5 * resultant of 1 25
4. 4 * Y 12
5. Resultant of 4 / resultant of 2 1
6. Resultant of 3 – resultant of 5 24
Example : evaluating a relational expression .

A–2 B
uses the following values to evaluate the expression :
A = 6 b= 8
Operation resultant
1. A – 2 4
2. Resultant of 1 B false
Example : evaluating a logical expression .

A AND B OR C AND A
uses the following values to evaluate the expression :
A = true B = false C = true
Operation resultant
1. A AND B false
2. C AND A true
3. Resultant of 1 OR resultant of 2 true
Straight-Line Form
68

Algebraic Expressions cannot be represented in the


computer.
They must be converted to a form the computer will
recognize.
Thus, Straight Line Form

(X Y)
Y = (X – Y) / ( (X + Y)^2 / (X – Y )^2 )
(X Y )2
(X Y )2 straight line form
Attachment: ASCII Coding
69

COP1006 McManus
1

PROGRAMMING
CONCEPTS
Chapter 3
Communicating with the computer
2

you have to learn its system of communication or


language .
The meaning of an instruction is essentially the same
in many computer language or application.
Syntax refers to the rules governing the computer
operating system , the application, and the
languages.
An errors is called a bug .
A process called debugging .
Communicating with the computer
3

many bugs are result of syntax errors but some


are logic errors .
All syntax errors must be corrected before you
execute and test your program .
Organizing the Problem
4

Certain organizational tools will help you learn to


solve problems on the computer .

The tools include the:


Problem Analysis Chart (PAC)
Structure/Interactivity Charts
Input Processing Output (IPO) Chart
Algorithms.
Flowcharts
Analyzing the problem
5

Understand the Problem


Analyze the Requirements of the Problem
A good way to analyze a problem is to separate
it into four parts, problem analysis chart( PAC) :
1. The given data.(constant and variables)
2. The required results.(the out put)
3. The processing that is required in the problem
.(equations and expressions)
4. A list of solution alternatives .
Problem Analysis Chart (PAC)
6
PAC Payroll Example
7

Calculate the gross pay of an employee. The formula


to be used is
GrossPay=Hours*PayRate

Develop PAC for a solution to this problem?


PAC Payroll Example
8
Interactivity (Structure) Chart
9

Divide processing into subtasks called modules


Then connect these modules together to show the
interaction of processing between modules.
Each modules should contain the tasks to
accomplish one function.
There will be one module that controls the flow to
most of other modules called the Control or main
module .
The subtasks of this module are then located
below it in the structure chart .
The Interactivity Chart
10
The Interactivity Chart
11

Indicates duplicate modules by darkening the upper


left-hand corner of each module.

The darkened circles indicate that the module is


part of a set of modules that are processed many
time – those in loop .
The Interactivity Chart
12

The diamond on the vertical line above the box


indicates which modules are involved in a decision .

Annotation may be placed beside the circle or


diamond to indicate the condition
The Interactivity Chart for the Payroll
13
Problem
Developing Input Processing Output
14
(IPO) Chart

IPO chart shows:


What data item are input
What processing takes place on that data
What information will be the end result, the output
Where in the solution the processing takes place.
The IPO Chart for the Payroll Problem
15

The module references are show which will perform


each step in the processing
Writing the Algorithm
16

The next step of organizing a solution is to develop


sets of instructions for the computer, called
algorithms.
The programmer writes a separate set of instructions
for each module in the structure chart .
The number of instruction is determined by the way
the programmer chooses to solve the problem .
17

The Form of an Algorithm

• The Control module uses an End since this is the end of the processing
. The other modules use Exit because the processing continues .
Drawing the Flowchart
18

Graphic representations of the algorithms.


The algorithms and flowcharts are the final steps in
organizing a solution.
A flowcharts shows the flow of the processing from
the beginning to the end of a solution.
Each block in a flowchart represents one instruction
from an algorithm.
Drawing the Flowchart
19

Flowlines indicate the direction of the data flow.


Most block have one or more entrances
Most block have only one exit .
Since ,in most cases , data can flow to only one other
block .
Exception a block representing a decision instruction
A loop enables the computer to perform a task
repeatedly during the processing of solution .
Flowchart Symbols
20
21
Flowchart Symbols
22
Flowchart Symbols
23
The algorithms and Flowcharts
for the Payroll Problem
24
The algorithms and Flowcharts
for the Payroll Problem
25
26

Order of
Execution of
Instructions
Algorithm and Flowchart Form
27
Pseudocode
28

Peseudocode is similar to the algorithm without the


numbers and details.
It closely follows the algorithm, but is characteristically
closer to what you would write in a computer
language.
Pseudocode
29
Documentation
30

Documentation

Internal External
documentation documentation
Internal Documentation
31

Is a file contains:
People who worked on the program
List of all variable name (details).
Note about the development of the program
External Documentation
32

For the user of the program.


Include any thing that allow the user to learn to use
the program in the least amount of time (what
should to do and what should not do).
Coding the solution
33

Select the appropriate language


Code the program
Testing the solution
34

Test the a solution to make sure it meet the


requirements of the user ,the all instruction on program
is correct without any error if a bug is detected the
solution has to be modified to correct it.
Algorithm Instructions

- For example, the square root function is used in an assignment statement as follows:
A = Sqrt(X) + 7
Therefore, the result of the square root of X would be returned in the name of the
function. This value is added to 7 and then stored in A.

The Write instruction outputs values to the printer. The list of information to be printed
follows the Write, as in
Write Name, Age
- The Print instruction is similar to the Write instruction expect that the output is directed
to the screen rather than the printer.

35
Algorithm Instructions (continues)

36

The End, Exit, or Return instruction specifies the completion of a module.


End is used to end the Control module and indicates that the processing of the
solution is complete.
Exit is used to end a subordinate module if there is no return value, and indicates
that the processing will continue in another module, the module where the Process
instruction originated
- The Return (variable) is used to place a value in the name of the module. The Return
is used when the module is to be processed within an expression.
An Example
37

1- Enter a name and an age into the computer.


2- Print a name and an age on the screen.

The algorithm and ( )


flowchart to enter a name
and age into computer
and print it on the screen.

Notice that the algorithm


instructions are numbered
starting with the first instruction
after the name of module
Problem Solving with Decisions

1 T.Fatin Alhila
Decision Logic Structure

- The decision structure is one of the most powerful structures because


it is the only way that the computer can choose between two or more
sets of actions.
- The decision logic structure uses the:
If/Then/Else instruction.
- It tells the computer that If a condition is true, Then execute a set of
instructions, or Else execute another set of instructions.
- The Else part is optional.

2 T.Fatin Alhila
Common Forms of decision structure
•If <condition(s)>
•Then
T •<True instructions>
•Else
F
•<False instructions>

3 T.Fatin Alhila
Decision Logic Structure

- A condition can be one of four things:


a- A logical expression. An expression that uses logical
operators (AND, OR, and NOT).
b- An expression using relational operators (<, <=, >, >=,
=, and < >).
c- A variable of the logical data type (True, False).
d- A combination of logical, relational, and mathematical
operators.

4 T.Fatin Alhila
Decision Logic Structure

- Some examples of conditional expressions are as follows:


1. A < B
A and B are the same data type either numeric,
character, or string.
2. X + 5 > = Z
X and Z are numeric data.
3. E < 5 OR F > 10
E and F are numeric data.
4.Y – X < 5 + Z
Y, X, and Z are numeric data.
5 T.Fatin Alhila
Decision Logic Structure

- Logical operators are used to link more than one condition together.

- The programmer can set up the condition for a decision through the use
of operands and various operators.

6 T.Fatin Alhila
Decision Logic Structure

- These conditions can be used alone or linked with other conditions for
use in the instruction.
- The programmer derives the information needed to set up the
condition(s) for a decision from the problem itself during problem
analysis.
- The True branch and the False can come from any of the lower three
points of the diamond.
- The convention is to draw the True branch on the right and the False
branch on the left or bottom, although it depends on the decisions to be
made.

7 T.Fatin Alhila
Common Forms
The If Statement
The Single Selection If/Then
The Double If/Then/Else
The Multiple If/Then/Else
Straight-through Logic
The Case Statement
The Switch Statement

8 T.Fatin Alhila
1- Single Selection: If/Then
one condition one instruction(true section) no else part

write an algorithm and corresponding flowchart


that read a student grade on a test which is out
of 10, then alerts the student if his grade is
under 4.

9 T.Fatin Alhila
Algorithm Flowchart
StudentAlert()
1. Integer grade StudentAlert()
2. Enter grade
3. If grade < 4 Integer grade
then
1. Print “Alert:You must study hard”
1. end Enter grade

F T
If grade < 4

Print “Alert:You
must study hard”

End
10 T.Fatin Alhila
2- Double If/Then /Else Selection
one condition two instruction –true-false-else part

write an algorithm and corresponding


flowchart to calculate the pay at an hourly rate,
and overtime pay (over 40 hours) at 1.5 times the
hourly rate.
hourly rate
Pay=PayRate * Hours

overtime pay
Pay=PayRate * (40 + 1.5 * (Hours-40))

11 T.Fatin Alhila
Algorithm Flowchart

PayCalculate()
1. Integer Hours, PayRate PayCalculate()
2. Enter Hours, PayRate
3. Real Pay
4. If Hours > 40 Integer Hours, PayRate
1. Then
1. Pay=PayRate * (40 + 1.5 Enter Hours, PayRate
* (Hours-40))
2. Else Real Pay
1. Pay=PayRate * Hours
5. End
F If Hours > T
40

Pay=PayRate * (40
Pay=PayRate * + 1.5 *
Hours (Hours-40))

12
End T.Fatin Alhila
3- Multiple Double If/Then /Else Selection

- Decision in which you have multiple conditions that lead to one action
or set of actions for True and False are slightly more complicated than
those with single condition.

- In these decisions you will use logical operators to connect the


conditions.

- The decision structure becomes more complicated as the number of


conditions and/or the number of actions for a True or False resultant
increases.

13 T.Fatin Alhila
Using Straight-through logic

Straight-through logic means that all of the decisions are processed


sequentially, one after the other.

There is no Else part of the instructions; the False branch always goes
to the next decision, and the True branch goes to the next decision
after the instructions for the True branch have been processed.

With decisions following Straight-through logic, all conditions are


tested. To test a condition means to process a condition to get a True or
False resultant.

14 T.Fatin Alhila
Using Straight-through logic

- Straight-through logic is the least efficient of all types of decision logic


Why??

- You must use it to solve certain problems, those that require two or
more unrelated decisions, and those in which all decisions must be
processed.

15 T.Fatin Alhila
Straight-Through Logic Example
Write an algorithm to change the value of X to 0 when X becomes greater
than 100, and to change the value of Y to 0 when Y becomes greater than
250.

X > 100 X=0

Y > 250 Y=0

16 T.Fatin Alhila
Straight-Through Logic Example
Algorithm Flowchart
ChangeValue()
ChangeValue()
1. Integer X,Y
2. Enter X,Y Integer X,Y
3. If X > 100
1. Then
1. X= 0 Enter X,Y
4. If Y > 250
1. Then T
If X > 100
1. Y= 0
5. End X =0
F

T
If Y > 250

F Y =0

17 End T.Fatin Alhila


Logic Conversion

- Sometimes you have to change the logic from positive to negative or


vice versa in order to improve the efficiency or readability of a solution.

- In a decision, there must always be instructions for a True section, but


not always for a False section. If there are no instructions for the True
section of a decision instruction, then it is better to convert the logic
type.

18 T.Fatin Alhila
Logic Conversion
Rules to convert from positive logic to negative logic or vice
versa:
Change all < to >=
Change all <= to >
Change all > to <=
Change all >= to <
Change all = to <>
Change all <> to =
Interchange all of the Then set of instructions with the
corresponding Else set of instructions.

19 T.Fatin Alhila
- For example:
It is to find the amount to charge people of varying ages for a concert
ticket. When the person is under 16, the charge is $7; when the person
is 65 or over, the charge is $5; all others are charged $10.

The conditions are the following:


Age Charge
Age < 16 $7
Age > = 16 and Age < 65 $10
Age > = 65 $5
20 T.Fatin Alhila
Example
Algorithm Flowchart
CalculateCharge() CalculateCharge()
1. Integer age , Charge
2. Enter age Integer age, Charge
3. If age < 16
1. Then
Enter age
1. Charge = 7
2. Else
1. If age < 65 F If age < T
1. Then 16
1. Charge = 10 F If age < T Charge = 7
2. Else 65
1. Charge = 5 Charge = 5 Charge = 10

4. End

End

21 T.Fatin Alhila
Figure 6.12 Conversion from Positive Logic
to Negative Logic

22 T.Fatin Alhila
Figure 6.12 Conversion from Positive Logic
to Negative Logic

23 T.Fatin Alhila
Decision Table
A good way to simplify the process of discovering
complicated actions and conditions is to draw a decision
table.
Most consist of 4 parts:
1. The conditions
2. The actions
3. The combinations of True and False for the conditions
4. The action to be taken or the consequences for each
combination of conditions.

24 T.Fatin Alhila
Table 6.1 Decision Table Format

• The total number of possible combinations of True or False for the conditions is
2^ #conditions

25 T.Fatin Alhila
Decision table Example
Set up a decision table for a store policy for charging a purchase.
There are three conditions:
1. The purchase is less than $100.
2. The last payment to the account was made in the last 30 days.
3. The balance of the account is less than $1000.
The following actions could be taken:
1. Credit is okay, and the customer can charge the item.
2. Refer the customer to the credit department.
3. Credit is denied and the customer cannot charge the item.

26 T.Fatin Alhila
Table 6.2 Decision Table

27 T.Fatin Alhila
Decision Table
The four steps to develop a flowchart from the decision table
are:
1. Draw all decisions in flowchart form.
2. Compare the true and false sides of each decisions, starting
with the first one.
3. Eliminate any decisions that have the same instructions on
both the true and false sides, keeping the true consequence
or action.
4. Redraw the flowchart.

28 T.Fatin Alhila
Development of flowchart from the
Decision table.

29 T.Fatin Alhila
Elimination of Conditions

30 T.Fatin Alhila
Final Flowchart

31 T.Fatin Alhila
Decision Table Example#2
Set up a Decision Table for Numeric Grades associated with
Letter Grades?

A 90-100
B 80-89
C 70-79
D 60-69
F Below 60

32 T.Fatin Alhila
Decision Table Solution

Letter Grade
(Solution-Action)
A B C D F
Numeric Grade
(Condition)
90 <= n X
80 <= n < 90 X
70 <= n < 80 X
60 <= n < 70 X
< 60 X
33 T.Fatin Alhila
let’s work a problem

(Putting It All Together)

34 T.Fatin Alhila
Putting It All Together

The Putting It All Together (PIAT) are designed to show that how to
pull together and use the concepts from a previous sections.

The PIAT demonstrates how to use the six steps of problem solving on
the computer to develop a solution that uses the sequential and the
decision logic structures.

35 T.Fatin Alhila
Putting It All Together

- For example:
The Floral Company sells to wholesale and retail buyers. The wholesale
buyer needs a resale number in order to buy at no tax and to receive
discounts. The retail buyer pays 6% tax.

These are the discounts to the wholesale buyer:


Amount < $100 Discount = 2%
Amount > = $100 AND < $500 Discount = 5%
Amount > = $500 Discount = 10%

36 T.Fatin Alhila
A Fantastic Floral Company_
PAC (Problem Analysis Chart)

37 T.Fatin Alhila
Fantastic Floral Company –
Interactivity (Structure) Chart

38 T.Fatin Alhila
Fantastic Floral Company – IPO Chart

39 T.Fatin Alhila
Coupling Diagram and Data Dictionary

...
40 T.Fatin Alhila
The Algorithms and Flowcharts –
Control Module

41 T.Fatin Alhila
The Algorithms and Flowcharts –
Read Module

42 T.Fatin Alhila
The Algorithms and Flowcharts –
Calc Module

43 T.Fatin Alhila
The Algorithms and Flowcharts
Print Module

44 T.Fatin Alhila
PROBLEM SOLVING WITH
LOOPS
Chapter 7
Concept of Repetition Structure Logic

It is a computer task, that is used for Repeating a


series of instructions many times.
Ex. The Process of calculating the Total Payment for more
than one employee.

Loops can be written using combination of previous


logic structures
Example:

Write an Algorithm that calculate the average of 7


students grade.
Solution without looping structure
Real St1_Grade, St2_Grade, St3_Grade, Read()
St4_Grade, St5_Grade, St6_Grade, 1. Read St1_Grade
2. Read St2_Grade
St7_Grade,
3. Read St3_Grade
Control () 4. Read St4_Grade
1. Read() 5. Read St5_Grade
2. Average() 6. Read St6_Grade
3. End 7. Read St7_Grade
8. Exit

Average()
1. Real Sum, Average
2. Sum = St1_Grade+St2_Grade+St3_Grade+ St4_Grade+St5_Grade+St6_Grade+ St7_Grade
3. Average = Sum/ 7
4. Exit
Solution with looping structure

Average()
Real Student_Grade 1. Integer Count=1
Control () 2. Real Sum=0
3. While ( count <= 7)
1. Read() 1. Read()
2. Average() 2. Sum=Sum +Student_Grade
3. Count=Count+1
3. End 4. WhileEnd
5. Real Average = Sum / count
6. Exit
Read()
1. Enter Student_Grade
2. Exit
Average Module Algorithm Flowchart
Flowchart
What will
Happen If What will
Average()
we Happen If Sum has no initial
remove we
this? value, its value is
Integer Count=1 remove
this?
Unknown
Real Sum=0
Count has no
data, its value is F T
While
Unknown, So the Count<=7
value of the
condition is Read() What will
unpredictable. Happen If
Real Average = Sum / 7 we
Sum=Sum+Student_Grade
remove
this?
Exit Count=Count+1

This will lead to


an infinite loop
The loop logic structure
There are three types of loop structures:
The While/WhileEnd loop
Which repeats instructions while a condition is True and
stops repeating when a condition arises that is not True .
The Repeat/Until loop
Which repeats instructions while a condition is False or until
a condition is True .
The automatic-counter loop
a variable is set equal to a given number and increases in
equal given increments until it is greater than an ending
number .
The loop logic structure
The algorithm and flowchart differ with each type of
loop structure .
Several standard types of tasks are accomplished
through the use of the loop structure .
Counting ( incrementing and decrementing)
Accumulating ( calculating a sum or a total)
In both task a number is added or subtracted from a variable
and the result is stored back into the same variable .
In each case the resultant variable is assigned the value of zero
before starting the loop( initializing the variable ) .
Initialization
The Initialization
set to an initial value
usually zero but not all the time
Examples:
Count = 0
Count = 1
Count = 100
Incrementing (or Decrement)
Is done by adding a constant , such as 1 or 2 to the
value of a variable
Example :
Counter = counter + 1 or c=c+1
Note: Remember Variable Must be
Initialized before starting the loop.

The increment can be one , two , or any other constant


, including negative number if you want to decrement
rather than increment .
Example:
Counter = counter -1 or c=c-1
The Accumulating
Or summing , a group of numbers
Similar to incrementing, except a variable instead of
a constant is added to another variable.
sum = sum + variable or s = s + v

Examples:
Totalsales = Totalsales + Sales

Note: Remember Variable Must be


Initialized to zero.
While/ While End Loop.
Repeats the instructions between the While & While End, if the
condition is true.

While <Condition (s)>


Instruction
Instruction
.
.
.
WhileEnd
while/whileEnd
Use the While/ While End Loop structure when you do not
know the number of times an instruction to be repeated.
Or if there are cases when the instructions in the loop
should not be processed .
Primer read The value must be entered before the loop
start.
It gives the while/whileEnd loop a valid value for the
variable in order for the conditions to be true the first time
through the loop .
The value of variable that allow to control when to stop
the looping process called a trip value .
Example 1:

Create the algorithm to find the average age of all the


students in class

How many UNKOWN


Students?

How can I solve this


problem?
Average Age of a
Class –
While/WhileEnd
Repeat/Until

Repeat
Instruction
Instruction
.
.
.
Until< Condition(S)>
Example 1:

Create the algorithm to find the average age of all the


students in class

How many UNKOWN


Students?

How can I solve this


problem?
Average Age of
a Class –
Repeat/Until
While/EndWhile & Repeat/Until

While/WhileEnd Repeat/Until

•You must initialize the data so that the •You can set the operand of the conditions
resultant of the condition is true the first anywhere within the loop since the
time through the loop. Otherwise , the loop condition is processed at the end .
instruction will never be processed . •Repeat the loop until the resultant of
•Repeat the loop until the resultant of condition is true.
condition is false. •The condition is processed at the end
•The condition is processed at the beginning •Instructions in the loop are processed
entirely at least once.
Automatic-Counter Loop
Increments or decrements a variable each time the
loop is repeated .
Use it when you know from the start the number of
times the loop will be executed .
The beginning value , the ending value , and the
increment value may be constant , variable , or
expressions .
Automatic-Counter Loop

Variable name
Loop: counter=begin To End Step S
Instruction
Instruction
Instruction
.
.
Loop –End: Counter
Automatic-Counter Loop:
General Rules

When the computer executes the Loop instruction its sets the
counter equal to the beginning number.

When the computer executes the Loop-End instruction it


increments the counter.

When the counter is less than or equal to the ending number


The processing continues for the instructions that follows the loop.

When the counter is greater than the ending number.


The processing continues for the instructions that follows the loop-End
instruction.
Automatic-Counter Loop
When decrementing the counter :
The counter is decremented at the end of the loop .
When the counter is greater than or equal to the ending
value , the loop continues.
Step value needs to be a negative number and begin must
be greater than end
Example 1: using Automatic-Counter Loop

Create the algorithm to find the average age of all the


students in class
2

3 ( J -1 )
4 J,
5

( J – 1)

J,
Example 2:
Create the algorithm & flowchart to:
Prints the even numbers.
The series of numbers will:
Start From 0 .
Ends at 50.
Example 2 Solution

Algorithm
PrintEvenNum()
1. Loop: counter=0 To 50 Step 2
1. Print counter
2. Loop-End: counter
3. End
Recursion
Another type of loop structure .
A module or a function calls itself .
Example :

FactorialFunction (N)
1. If N > 1
then
Factorial = N * FactorialFunction (N-1)
Else
Factorial = 1
2. Exit

You might also like