69
BEGINNING PROBLEM-SOLVING CONCEPTS FOR THE COMPUTER Chapter 2 1

BEGINNING PROBLEM-SOLVING CONCEPTS FOR · PDF file12/3/2011 · BEGINNING PROBLEM-SOLVING CONCEPTS FOR THE COMPUTER Chapter 2 1. 3 Types of Problems that can be solved on computers

Embed Size (px)

Citation preview

BEGINNING PROBLEM-SOLVING

CONCEPTS FOR THE COMPUTER

Chapter 2

1

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

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.

8

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).

Constant Name Variable Names

PI

KCONATANT

MULTIPLIER

PayRate

Rate

HoursWorked

Amount

Tempreature

StudentName

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.

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.

17

Data

Data

Processed

into Information

Report

Balance

Sheet

Calculates the

Balance

Checks

Deposits

Bank Charge

Input Output

Processing Data – How a computer

Balances a Checkbook

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 +

decimal)

3456.78

0.000123

Character (uses

quotation marks)

All letters, numbers, and

special symbols

“A”, “a”, “1”, “5”, “+”,

“%”

String (uses quotation

marks)

Combinations of more than

one character

“Mulder”

“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

Dec Char Dec Char

97 a 65 A

98 b 66 B

99 c 67 C

100 d 68 D

101 e 69 E

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

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

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

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

26

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

McManus COP1006

27

Comparing Characters & Strings

Comparing Characters & Strings

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).

28

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

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.

33

Rules for Data Types

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”

34

Examples of Data

Types

Data Type Data

Numeric

Real

The price of item

4.25

String Account number

“1234567”

Numeric

Integer

Room numbers

112

String Name of company

“Apple Macintosh”

Logical Check status

Pass/Fail

True or False

Date or

String

Date

12/3/2011

McManus

36

COP1006

How the Computer Stores Data

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:

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

Middle String Mid(s, n1, n2)

Mid(S,3,2) where

S = "Thomas" "om"

Left String Left(s, n)

Left(S,3) where S

= "Thomas" "Tho"

Right String Right(s, n)

Right(S, 3) where

S = "Thomas" "mas"

Length String Length(s)

Length(S) where S

= "Thomas" 6

Conversion Functions 43

Function Form Example Result

Valued ConversionValue(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 Result Exampl

e

Definition Functio

n

09/15/08 Date Returns the current date from the

system. The date may be in various

forms:

mm/dd/yy, day only, month only, year

only, or Julian calendar

Date

9:22:34 Time Returns the current time from the

system. The time may be in various

forms:

hh:mm:ss, seconds from midnight, or

minutes from midnight

Time

Returns control to the program when a

systems error occurs.

Error

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

Resultant Operation Compute

r Symbol

Operator

8.2 3.0 + 5.2 + Addition

3.5 7.5 – 4.0 - Subtraction

40.0 8.0 * 5.0 * Multiplication

2.25 9.0/4.0 / Division

2 9\4 \ Integer division

1 9 MOD 4 MOD Modulo division

9 3^2 ^ Power

Relational Operators

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

51

Relational operatores

Resultant Operation Computer

Symbol

Operator

False 5 = 7 = Equal to

True 5 < 7 < Less than

False 5 > 7 > Greater than

True 5 < = 7 < = Less than or equal to

False 5 > = 7 > = Greater than or equal to

True 5 < > 7 < > Not

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

Resultant Operation Compute

r Symbol

Operator

False NOT True NOT Not

True True AND True AND And

True True OR False OR Or

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

Resultant Data Type Operand Data Type Order of Operations

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

parentheses using the same hierarchy

Numeric Numeric Power ^

Numeric Numeric \, MOD

Numeric Numeric *, /

Numeric Numeric +, _

Logical Numeric or string or

character

=, <, >, < =, > =, < >

Logical Logical NOT

Logical Logical AND

Logical Logical OR

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

A and B are numeric.

The resultant is numeric and is not stored

C= A + B

C ,A and B are numeric.

The resultant is stored in C .

A < B

A and B are numeric , character, or string.

The resultant is logical and is not stored .

C = A < B

A and B are numeric , character, or string .

The resultant is stored in C ;

C is logical.

A OR B

A and B are logical .

The resultant is logical and is not stored

C = A OR B

C ,A and B are logical .

The resultant is stored in C .

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

68

Straight-Line Form

Algebraic Expressions cannot be represented in the

computer.

They must be converted to a form the computer will

recognize.

Thus, Straight Line Form

2

2

)(

)(

)(

YX

YX

YXY

= (X – Y) / ( (X + Y)^2 / (X – Y )^2 )

straight line form

Attachment: ASCII Coding

McManus COP1006

69