+ All Categories
Home > Documents > CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A...

CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A...

Date post: 10-Apr-2018
Category:
Upload: phungtruc
View: 218 times
Download: 5 times
Share this document with a friend
12
1 CPSC1620A Fundamentals of Programming I Summer Session I - 2013 Instructor: Arie Bomhof - Office: C510 Text: C++ Programming: From Problem Analysis to Program Design. 6th Edition D. S. Malik Introduction: Computers and Programming Programming – planning or scheduling the performance of a task or an event Computer – A programmable device that can store, retrieve, and process data. Computer Programming – The process of planning a sequence of steps for a computer to follow. 13 May 2013 CPSC1620 2 Brief History of Computers Abacus (ancient Babylon, China) 1642 – Blaise Pascal, von Liebniz – Pascaline, devices that could add, subtr, mult, and div. 1819 – Jacquard loom – instructions for weaving stored on cards with holes. 1840 – Charles Babbage – Difference Engine. More sophisticated operations, like squaring. Key idea here is that the technology did not exist to manufacture the "engine". One was built in 2002. 1840 – Ada Lovelace – first computer programmer. 1904 – Herman Hollerith – created electrical machine for US census. Began IBM company 13 May 2013 3 CPSC1620 History con't 1944 – Mark I – Harvard University - first computer-like machine. Used punched cards to enter data. 1946 – ENIAC (Electronic Numerical Integrator and Calculator). Programs were run by first connecting wires. 18000 vacuum tubes (switches) 1946 - Dr. John Von Neumann – Princeton University, proposed concept of a stored program computer – whose program is stored in computer memory. 1951 UNIVAC sold to US Census Bureau 1956 – Mauchly – invented transistor (Bell labs). These switches drastically changed computers b/c of their reliability. 13 May 2013 4 CPSC1620 History con't 1950's – first programming languages FORTRAN (FORmula TRANslating and COBOL (Common Buisness Oriented Language) 1960's – integrated circuits – many, many smaller and smaller transistors on a circuit board. They give us processing speed. 1970's – microprocessor – entire computer on a single chip 1977 – Steve Jobs, Steve Wozniak – first personal computer, Apple. 1981 – IBM PC (DOS operating system -> Windows) 13 May 2013 CPSC1620 5 13 May 2013 CPSC1620 6 18,000 vacuum tubes (switches) 100 feet long, 10 feet high. weighed 30 tons. could multiply 2 numbers in 1/300 s. Programs need to be hard wired ENIAC Electronic Numerical Integrator and Calculator
Transcript
Page 1: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

1

CPSC1620A Fundamentals of Programming I

Summer Session I - 2013

Instructor: Arie Bomhof - Office: C510

Text: C++ Programming: From Problem

Analysis to Program Design. 6th Edition

D. S. Malik

Introduction: Computers and Programming

• Programming – planning or scheduling the performance of a task or an event

• Computer – A programmable device that can store, retrieve, and process data.

• Computer Programming – The process of planning a sequence of steps for a computer to follow.

13 May 2013 CPSC1620 2

Brief History of Computers

• Abacus (ancient Babylon, China)

• 1642 – Blaise Pascal, von Liebniz – Pascaline, devices that could add, subtr, mult, and div.

• 1819 – Jacquard loom – instructions for weaving stored on cards with holes.

• 1840 – Charles Babbage – Difference Engine. More sophisticated operations, like squaring. Key idea here is that the technology did not exist to manufacture the "engine". One was built in 2002.

• 1840 – Ada Lovelace – first computer programmer.

• 1904 – Herman Hollerith – created electrical machine for US census. Began IBM company

13 May 2013 3 CPSC1620

History con't • 1944 – Mark I – Harvard University - first computer-like

machine. Used punched cards to enter data.

• 1946 – ENIAC (Electronic Numerical Integrator and Calculator). Programs were run by first connecting wires. 18000 vacuum tubes (switches)

• 1946 - Dr. John Von Neumann – Princeton University, proposed concept of a stored program computer – whose program is stored in computer memory.

• 1951 UNIVAC sold to US Census Bureau

• 1956 – Mauchly – invented transistor (Bell labs). These switches drastically changed computers b/c of their reliability.

13 May 2013 4 CPSC1620

History con't

• 1950's – first programming languages FORTRAN (FORmula TRANslating and COBOL (Common Buisness Oriented Language)

• 1960's – integrated circuits – many, many smaller and smaller transistors on a circuit board. They give us processing speed.

• 1970's – microprocessor – entire computer on a single chip

• 1977 – Steve Jobs, Steve Wozniak – first personal computer, Apple.

• 1981 – IBM PC (DOS operating system -> Windows)

13 May 2013 CPSC1620 5 13 May 2013 CPSC1620 6

• 18,000 vacuum

tubes (switches)

• 100 feet long, 10

feet high.

• weighed 30 tons.

• could multiply 2

numbers in

1/300 s.

• Programs need

to be hard wired

ENIAC Electronic Numerical Integrator and Calculator

Page 2: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

2

John Von Neumann

• Brilliant mathematician

• worked on the ENIAC

• proposed to put

instructions into memory

• up to this time all instructions were “wired” in.

• instructions to be encoded as binary values and stored along with the data

13 May 2013 CPSC1620 7

Computer’s architecture

• Computers are organized into four main parts 1. CPU - central processing unit

• brains of the computer, most expensive part. • eg. Pentium 4, AMD Athlon

2. Main Memory • stores information being processed by the CPU • eg. 4 GByte

3. Secondary Storage • stores data and programs • eg. 1TByte Hard drive

4. Input/Output devices

• allows people to supply information to and from computers • eg. printers, scanners, speakers, monitors, etc.

13 May 2013 CPSC1620 8

Four main parts: Input/Output Devices, CPU, Memory, Storage.

Computer: Hardware

9

1. CPU - consists of: • CU – Control Unit – it has 3 functions:

– fetch and decode instructions

– control flow of information (instructions or data)

– control operations of the CPU’s internal components.

• ALU – Arithmetic Logic Unit – carries out all arithmetic and logic operations

• PC – program counter, points to next instruction

• IR – instruction register holds instruction currently being executed

• ACC – Accumulator – holds results of ALU

13 May 2013 CPSC1620 10

CPU con’t

• Fundamental building

block in CPU is a

switch

– made from ultra-small

transistors, capacitors,

and wires. Example:

• The Core i7 Extreme Edition has about 1.3 billion transistors

• Moore's Law: the number of transistors that can be placed inexpensively on an integrated circuit has increased exponentially, doubling approximately every two years.

13 May 2013 CPSC1620 11

Evolution of CPU

Processor Year # of Transistors Microns Clock Speed Data Width MIPS

8080 1974 6,000 6 2 MHz 8 bits 0.64

8088 1979 29,000 3 5 MHz 16 bits 8-bit bus

0.33

80286 1982 134,000 1.5 6 MHz 16 bits 1

80386 1985 275,000 1.5 16 MHz 32 bits 5

80486 1989 1,200,000 1 25 MHz 32 bits 20

Pentium 1993 3,100,000 0.8 60 MHz 32 bits 64-bit bus

100

Pentium II 1997 7,500,000 0.35 233 MHz 32 bits 64-bit bus

~300

Pentium III 1999 9,500,000 0.25 450 MHz 32 bits 64-bit bus

~510

Core Duo 2006 291,000,00 0.065 2.67MHz 32 bits 64-bit bus

~9500

Quad Core 2008 800,000,000 0.045 3.6 GHz 32 bits 64-bit bus

~18500

12

Page 3: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

3

2. Main (Primary) Memory • Connected to CPU.

• Stores: programs, data, results.

• Two types:

– RAM (Random Access Memory)

• Consists of cells (each with a unique address) that hold data or instructions

• Volatile (lost when power turned off)

• Computers today typically have around 1 to 3 GB for main memory

– ROM (Read Only Memory)

• Permanent

• where the boot-up instructions are stored

• Note: Most of today’s CPUs have cache memory built into the CPU. (4MB today) This is extremely fast memory

• See : http://www1.ca.dell.com/content/products/productdetails.aspx/dimen_9200c?c=ca&cs=cadhs1&l=en&s=dhs

Memory Sizes

13 May 2013 CPSC1620 14

3. Secondary Memory (Storage)

• Semi permanent data-storage – Tapes, floppy disks, zip disks

(archaic)

– Hard drives

– CD Roms, DVDs

– USB flash drive (memory sticks)

• Secondary memory has much more storage capacity. Eg. 1TB vs 4GB

13 May 2013 CPSC1620 15

4. Input / Output Devices

• Input:

– Feed data and programs into the computer.

– Eg. keyboard, mouse, scanner, secondary storage.

• Output:

– Display or process results.

– Monitor, printer, secondary storage.

13 May 2013 CPSC1620 16

Software • “Programs that run on a computer”.

Two types: System Programs and Applications Programs

• System Programs control the computer.

• The main system program is the operating system – The operating system is a set of programs that manages the

computer’s hardware devices and controls their processes. It provides:

• File system

• Commands that allow for manipulation of the file system

• Ability to perform input and output on a variety of devices

• Written in a programming language.

Examples:

MSDOS ®, Windows ®, Unix ® (written in C), Linux

• Application programs – programs that make the computer useful to the user.

– word processors, spreadsheets, database management systems, photo editing, etc.

13 May 2013 CPSC1620 18

Programming Languages • “A set of keywords and grammar rules that a computer can process or

carry out”. • Two main types:

– Low Level: • machine language,

– hard to understand, seldom used anymore. – commands consist of only 0’s and 1’s, the “native tongue” of the computer. – eg. 010001 00101 may mean “load 5” into memory

• assembly language – use mnemonics or op codes like LDA for load instead of 010001 – eg. LDA 5 – but still hard to understand and follow.

– High Level: • Closer to natural language and easier to understand • eg. wages = hourlyRate * hoursWorked;

• High Level Language examples: BASIC, C, C++, Pascal, Fortran, Java, COBOL, APL, FORTH, LISP, etc.

13 May 2013 CPSC1620 19

Page 4: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

4

Programming Languages

• Any programming language should have: – a syntax (grammar and rules)

– portability – so can be used on any machine w/o modification.

• A program usually consists of: – source code (.cc for C++)

– object code (.o) or machine language.

– executable code (no extension for C++)

• All high-level language programs need to be converted to the computer’s native language (machine language).

13 May 2013 CPSC1620 20

Processing a High-Level Language Program

• How? With a translator.

• Two types of translators – Interpreters – translate and execute programs one

line at a time. • Ex. LISP, Prolog, BASIC use interpreters

– Compilers – translate entire programs into machine language, after which execution of the programs take place. • Ex. C, C++, Pascal, FORTRAN, COBOL use compilers

13 May 2013 CPSC1620 21

Processing a Program • An editor is used to enter a program.

– Source program: written in high level language eg. (myFile.cc)

– our machines, UNIX based, use text editors, te, vi, and emacs. We will use emacs.

• We use g++ (a free application program) to compile (translate) source programs into object programs (machine language).

– Syntax errors are displayed (not always descriptive, often cryptic).

• The linker/loader combines object file with other object files and produces the executable file

– eg. myProgram.cc myProgram.o myProgram

13 May 2013 CPSC1620 22

Processing a C++ Program

13 May 2013 23 CPSC1620

ANSI/ISO Standard C++

• C++ has evolved from C.

• Designed by Bjarne Stroustrup in 1980.

• ANSI/ISO standard allows for portability from one compiler to another.

• our g++ compiler complies with the new standard (1998).

13 May 2013 CPSC1620 24

Structured Programming

• Structured design:

– Dividing a problem into smaller subproblems

• Structured programming

– Implementing a structured design

• The structured design approach is also called

– Top-down design

– Stepwise refinement

– Modular programming

C++ Programming: From Problem Analysis to Program Design, Third

Edition 25

Page 5: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

5

Object Oriented Programming

• or OOD – object oriented design • Popular b/c of reuse of classes and objects. • An object is any specific item having certain attributes or

properties. • EG. A Volkswagon is an object that has all the attributes and

properties of an Automobile. • it has data: engine, # of doors, color, etc. • it can perform actions: start up, go ahead, go reverse, speed

up, brake, turn, etc. • Volkswagon is an instance of the class Automobile. • more on this towards end of course and nearly all of CS2620

deals with OOD.

13 May 2013 CPSC1620 26

Structure Programming and the Software Development Method

1. State the problem – Discuss the problem

• analyze the requirements • specify the requirements • determine the input and output • are there any constraints?

2. Analysis & Design – Break into smaller problems with – Top-down design (divide and conquer) – Develop an Algorithm

• a step-by-step problem-solving process in which a solution is arrived at in a finite amount of time.

• use an english like pseudocode.

13 May 2013 CPSC1620 27

Software Development Method

3. Implementation (coding) – Write the algorithm in desired language (C++ in

our case).

4. Testing – Does program meets requirements?

5. Maintain and document – Changes needed?

– Can others read your program?

– Put in comments (documentation).

13 May 2013 CPSC1620 28

Algorithms

• Should solve a given problem

• Should be unambiguous (not “fuzzy”)

• If problem has an end then algorithm should terminate after a finite number of steps.

13 May 2013 CPSC1620 29

Applying the Software Development Method

Example: 1. Problem Specification:

Compute and display the total cost of apples, given the number of kilograms of apples purchased and the cost per kilogram of apples.

13 May 2013 CPSC1620 30

2. Analysis (abstraction)

– Problem Inputs

• quantity of apples purchased in kg

• cost per kg of apples ($/kg)

– Problem Output

• total cost of apples (in $)

– Relevant Formulas

• total cost = kilograms of apples x cost/kg.

13 May 2013 CPSC1620 31

Page 6: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

6

Design: Develop an algorithm to solve the problem.

Begin by listing the three major steps, or sub problems, of the algorithm.

Algorithm 1. Get the input from the user

2. Do the calculations

3. Display the results

13 May 2013 CPSC1620 32

Design con’t

• Algorithm refinements.

1.1 Get the # of kilograms, kgs, of apples purchased.

1.2 Get the cost, c of the apples in $/kg.

2.1 Set totalCost, equal to kgs * c.

3.1 Print to the screen: “The total cost of the apples will be: <totalCost>”

13 May 2013 CPSC1620 33

Implementation and Testing

3. Implementation To implement the solution, you must write the algorithm in C++ code.

4. Testing How do you know the sample run is correct? Does the output make sense? You should always test for values that you know are true. Eg temperature conversion: Does 370C = 98.60F? or –400C = -400F?

5. Maintain and document by putting in comments where needed.

13 May 2013 CPSC1620 34

Program Development Cycle

35

Example 2

• Every salesperson has a base salary

• Salesperson receives $10 bonus at the end of the month for each year worked if he or she has been with the store for five or less years

• The bonus is $20 for each year that he or she has worked there if over 5 years

C++ Programming: From Problem Analysis to Program Design, Third

Edition 36

Example 2 (continued)

• Additional bonuses are as follows:

– If total sales for the month are $5,000-$10,000, he or she receives a 3% commission on the sale

– If total sales for the month are at least $10,000, he or she receives a 6% commission on the sale

C++ Programming: From Problem Analysis to Program Design, Third

Edition 37

Page 7: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

7

Example 2 (continued)

• Get baseSalary

• Get noOfServiceYears

• Calculate bonus using the following formula: if (noOfServiceYears is less than or equal to

five)

bonus = 10 * noOfServiceYears

otherwise

bonus = 20 * noOfServiceYears

• Get totalSale

C++ Programming: From Problem Analysis to Program Design, Third

Edition 38

Example 2 (continued)

• Calculate additionalBonus as follows: if (totalSale is less than 5000)

additionalBonus = 0

otherwise

if (totalSale is greater than or equal to

5000 and totalSale is less than 10000)

additionalBonus = totalSale · (0.03)

otherwise

additionalBonus = totalSale · (0.06)

C++ Programming: From Problem Analysis to Program Design, Third

Edition 39

Example 2 (continued)

• Calculate payCheck using the equation

payCheck = baseSalary + bonus + additionalBonus

C++ Programming: From Problem Analysis to Program Design, Third

Edition 40

Pseudocode, ex. 3 • Write a program that finds the average of the midterm exam scores (0% -

100%). The user will enter -1 to indicate end of data.

• Declare appropriate variables, eg, count, total, number, avg

• Set total = 0 and count = 0

• Ask user for a number.

• Is the number -1?

• If yes, stop, nothing to do

• While number != -1, repeat the following 3 steps – add number to total

– add 1 to count (ie. increment by 1)

– ask for another number

• set average to be total divided by count.

• output the average to the screen.

13 May 2013 CPSC1620 41

Pseudocode, Ex. 4

• Write a program that muliplies 2 numbers by repeatedly adding.

1. get numbers to multiply, n1 and n2

2. set product = 0;

3. set index = 1;

4. while index <= n2 do the following steps a. add n1 to product

b. increment index by 1

5. output product to the monitor.

13 May 2013 CPSC1620 42

Binary Number System • Before we get into writing C++ code we should understand how our

computers store numbers.

• Humans consider numbers in terms of decimals but computers only understand if electricity is on or off.

• The binary number system lends itself nicely to model this system, ie electricity on = 1, electricity off = 0.

• The basic memory unit of a computer is a byte (not bite to confuse it with bit).

• Each byte consists of 8 bits (binary digits) • Letter ‘D’ takes up one memory unit, or one byte. The bits that make up

the byte contain some representation of 1’s or 0’s ie 01000100. Electricity is flowing through the 2nd and 6th bits, whereas it is not in all the others.

13 May 2013 CPSC1620 43

Page 8: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

8

The Binary Number System • Humans use decimal system, 0,1,2,…,9.

• 26 letters of the alphabet.

• +/- sign represents positive or negative

• Floating point decimal; eg 0.56, 361.4

• Computers use this externally but internally they use the binary number system.

• Suppose you enter a 5 in an Excel spreadsheet. It is actually stored like:

00000000 (1st byte)

00000000 (2nd byte)

00000000 (3rd byte)

00000101 (4th byte…every integer takes up 4 bytes of memory)

• The graphics card in your computer “sees” this arrangement of numbers and then "draws" a 5 on your screen.

44

Binary Representation is Reliable

• Computers only respond to electric currents.

• if we had 10 electrical states (for decimal) it would lead to instability. ie. a +/- 2 volt leakage can change a 2 to a 1 or a 3.

• With binary, a +/- 2 volt drift is not a problem. ie going from 5 volts to 3 volts is still a positive voltage.

13 May 2013 CPSC1620 45

Binary Place Values

• In decimal, (base 10) we indicate place values by the order of digits

135 = (1*102) + (3*101) + (5*100)

• In binary only 0’s and 1’s exist and we do the same:

• 10011 = (1*24)+(0*23)+(0*22)+(1*21)+(1*20)

= 16 + 0 + 0 + 2 + 1

= 19

13 May 2013 CPSC1620 46

Converting Whole Numbers

• Whole numbers are the counting numbers 0, 1, 2, 3, 4, 5, 6, 7, 8 …

• In binary we count 0, 1, 10, 11, 100, 101, 110, 111, 1000, …

• To convert a binary whole number to a decimal multiply each digit by it’s place value:

11012=(1x20)+(0x21)+(1x22)+(1x23)=1+0+4+8=1310

• To convert a decimal whole number to a binary divide by two repeatedly and keep track of the remainders …

13 May 2013 CPSC1620 47

Converting Whole Numbers to 8-bit unsigned binary

13 May 2013 CPSC1620 48

So 1110=000010112

11 5 1 2 1 1 0 0 1

Read

up

So 1910=000100112

19 9 1 4 1 2 0 1 0

Read

up

0 1

Unsigned binary number limits • It takes more digits to represent a number in binary

than it does in decimal.

• The largest whole number that may be represented in 8 bits is 111111112=25510

13 May 2013 CPSC1620 49

Bits Range

3 0 – 7 (23-1)

8 0 to 255 (28-1)

32 0 to 232-1= +4,294,967,295

Page 9: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

9

Binary Integers – Integers are the positive and negative whole numbers

…, -3, -2, -1, 0 , 1, 2, 3, … – So how do we represent integers in binary? – Binary integers …, -11, -10, -1, 0, 1, 10, 11 … – But we can’t have a negative sign in memory. – So in “signed binary” we use the first bit as a sign bit with the rest

to represent the magnitude of the number. (1 means negative, 0 means positive)

• ie: in 8 bits, 100011112 = -15 and 000011112 = +15 • But we have a problem at zero! 100000002 or

000000002 ; -0 or +0?

– To avoid this issue, nearly all today’s computers use the Two’s Complement method to represent positive and negative numbers (we’ll see this later).

13 May 2013 CPSC1620 50

Signed binary integer limits

• The max value for integers is smaller than the max value for whole numbers.

• Roughly half of the values are now devoted to negative’s.

13 May 2013 CPSC1620 51

Bits Range

3 ±22-1 = ±3

8 ±27-1= ±127

32 ±231-1= ±2,147,483,647

77

+110

187

1001101

+1101110

1 1 0

1

1

1

1 1 10

23

+16

39

10111

+10000

1 1 1 0 10

31

-10

21

11111

-1010

1 0 1 0 1

34

-29

5

100010

-11101

10 0

1 0

1 1 10

1 0 0

Adding and Subtracting

Similar to elementary school addition and subtraction.

13 May 2013 CPSC1620 52

Two’s Complement • Most of today’s computers (including ours) use two’s complement method

to store integers.

• On our system integers are stored with 4 bytes or 32 bits. To explain two’s complement we will use only 1 byte or 8 bits so we don’t have to worry about so many digits.

• Converting to two’s complement (8-bit):

– If number is positive, change it to binary. Done.

– If number is negative: • change it to binary,

• complement the bits (change 1 to 0 and 0 to 1),

• add 1.

• If 1 is carried into the 9th bit, ignore it.

• When converting from Two’s Complement:

– If first bit is 0, convert as before.

– If first bit is 1: (you know the number is negative) • complement the bits, add 1, convert as normal,

• make it negative.

13 May 2013 CPSC1620 53

Converting in Two's Complement To two’s complement

• +1110= +10112 so 00001011 in 8 bits

• -1110= -10112 so 00001011 11110100

11110101 in 8 bits

• This solves the negative zero problem: -02: 00000000 11111111 add 1 100000000 00000000 in 8 bits

(we disregard the carry out bit)

From two’s complement

• 00001001 23+ 20=9

• 11110111 (this is negative)

00001000

00001001 -9

13 May 2013 CPSC1620 54

Two’s Complement Facts • The range of available numbers is increased by one since

we no longer have a negative zero.

13 May 2013 CPSC1620 55

Bits Range

3 -22 to 22-1 = -4 to +3

8 -27 to 27-1 = -128 to +127

32 -231 to 231-1=-2,147,483,648 to +2,147,483,647

In fact, 2,147,483,647 is the largest integer that you can use on our computers in the lab. If you try a larger integer at best you get

an overflow error or at worst, unpredictable results.

Page 10: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

10

Adding & Subtracting • In Two’s Complement adding & subtracting are the same thing. ie: to subtract

you need only add a negative number. • Remember, the computer does these calculations in lightning speed.

13 May 2013 CPSC1620 56

32

+7

00100000

00000111

------------

00100111 = 25 + 22 + 21 + 20 = 39

32

-7

00100000

11111001

------------

00011001 1 = 24 + 23 + 20 = 25

More adding & subtracting

13 May 2013 CPSC1620 57

32

-48

00100000

+11010000

0 0 0 0 1 1 1 1

48 = 001100002

Complement the bits

-48 is 11010000 in two’s complement

Complement the bits 00001111

Add 1 to get 00010000

000100002=24=16

Answer = –16.

Final answer will be negative since leading bit is 1

11001111 add 1

Converting Real Numbers

• Real numbers: any number including decimals.

1.23, 0.1439, 0.333333…, √2, ∏, etc.

• To convert a real number to binary:

– Convert the integer part as before.

– Convert the fractional part by repeatedly multiplying by 2 until the fractional part is zero.

• To convert a real number from binary:

– Multiply each 1 by it’s place value and add.

– Remember, in 0.9 the place value of the 9 is a tenth or 10-1 similarly the place value of the 1s in 0.1111…2 are 2-1, 2-2, 2-3, 2-4, …

13 May 2013 CPSC1620 58

Converting Real Numbers

13 May 2013 CPSC1620

59

So 5 = 1012 and 0.75=0.112 thus 5.75=101.112

5.75 5 2 1 1 0 0 1

Read

up

.75 1 .5 1 .0

Read

down

So 23 = 101112 and 0.3125=0.01012

thus 23.625=10111.01012

23.3125 23 11 1

5 1 2 1

Read

up

1 0 0 1

.3125 0 .625 1 .25

Read

down

0 .5 1 .0

Converting to Real Numbers

13 May 2013 CPSC1620 60

1101.1011012 = 23+ 22+ 20+ 2-1+ 2-3+ 2-4+ 2-6

=13.703125

1010.00012 = 23+ 21+ 2-4

=10.0625

101.000012 = 22+ 20+ 2-5

=5.03125

Decimal # Storage • There are two main types of decimal numbers in C++

programming, float and double.

• We would like to investigate how float and double numbers are stored in our computer.

• A float takes up 4 bytes while a double takes 8 bytes. So the maximum double value is greater than the maximum float value b/c we use more bits to represent it.

• Recall scientific notation: 352 = 3.52 x 102 = 0.352 x 103; 0.000352 = 3.52 x 10-4 = 0.352 x 10-3

• This process is called “normalization”

13 May 2013 CPSC1620 61

Page 11: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

11

Decimal storage • A float decimal number (32 bits) is stored in 3 segments.

• The first 23 bits (yellow) are for the fractional coefficient (with decimal point at front)

• The next 8 bits (green) are for the exponent

• The last bit (pink) is for the sign of the number.

• This fractional coefficient is actually: 110111 as we always shift the first ‘1’ out and assume it is there. This way we get 24 bits for the fractional coeff instead of 23.

• We need to be able to represent positive and negative exponents so we introduce a “bias” of 127. eg. +8 = 127 + 8 = 135; -3 = 127 – 3 = 124

13 May 2013 CPSC1620 62

1 0 1 1 1 0 0 0

0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 1

0 0 0 0 0 1 0 0

Decimal storage • Our exponent is 10000010. Now we need to “normalize” this by

subtracting 1111111 (127). 10000010 – 01111111 = 00000011 and this is equal to 3 in base 10.

• Our number is now 0.110111 x 23 = 110.1112 = 10.87510.

• So we see that decimal numbers are stored on computers differently than are integers.

• Suppose we declare float x = 208.95 in our C++ program.

• Because of the limited # of bits in our float we can never represent 208.95 EXACTLY! (For this reason we need to be careful when checking for equality of decimal numbers in C++ programs).

• 208.95 is: 11010000.111101001100110011001 = .11010000111101001100110011001 x 28.

• The exponent = 8, normalized = 8 + 127 = 135 = 10000111.

13 May 2013 CPSC1620 63

Decimal storage

• The exponent = 8, normalized = 135 = 10000111.

• The first yellow bit must be 1 so we assume it is there and then add a 1 in the end. In effect we have 24 bits for the fractional component instead of 23.

• What we see (in yellow) is 10100001111010011001100

• The exponent is 10000111. Now we need to “normalize” this by subtracting 1111111. 10000111 – 01111111 = 00001000 and this is equal to 8 in base 10.

• Our number is now 0.110100001111001100110011 x 28.

• 11010000.1111001100110011 = 208.9499969482421875 and this is not exactly 208.95

13 May 2013 CPSC1620 64

1 0 1 0 0 0 0 1

1 1 1 0 1 0 0 1

1 0 0 1 1 0 0 1

0 0 0 0 1 1 1 0

Characters in Binary

• Each character has a unique binary code. – ASCII (American Standard Code for Information Interchange) codes use

8 bits to encode characters, giving 256 possible codes.

– It is a most widely used code.

– Unicode uses 16 bits allowing 65536 different codes.

– Unicode provides a unique number for every character, no matter what the platform, no matter what the program, no matter what the language.

– All the ASCII codes are encompassed within Unicode.

• A byte like 01000001 could be interpreted as the letter A or the number 65. How its interpreted depends on the context.

13 May 2013 CPSC1620 67

Hexadecimal Number System • RAM addresses are usually given in hexadecimal (base 16).

• For example, in a C++ program we often declare variables. These variables take up memory, one of the 4GB of memory locations we might have available.

• Memory addresses are also stored as binary but it quickly becomes very inconvenient b/c of so many digits of 1’s and 0’s.

• This is where hexadecimal comes in. If we want to see where a variable is stored we might obtain something like: 0xbfa8420c.

• We know it is hexadecimal b/c of leading "0x".

13 May 2013 CPSC1620 68

Hexadecimal • In hex we count 0,1-9, A,B,C,D,E,F,10,11, 12, 13, 14,

15, 20, 21, etc…

• ex. 0x23 = 3*160 + 2*161 = 3510

• ex. 0x5F1= 1*160 + 15*161 + 5*162

= 152310

• A four digit binary number can represent values 0 to 15. Divide the binary number into groups of four and convert each group of 4 to a hex digit.

• To convert a hexadecimal number to binary we convert each hex digit to a four digit binary number.

13 May 2013 CPSC1620 69

Page 12: CPSC1620A Fundamentals of Programming I Summer …bomhof/lect/Malik_01.pdf · CPSC1620A Fundamentals of Programming I Summer Session I - 2013 ... • Abacus (ancient Babylon ... Blaise

12

Converting Hexadecimal

13 May 2013 CPSC1620 70

6A4E16 =>6 | A | 4 | E =>0110 | 1010 | 0100 | 1110

=>01101010010011102

10011010101111012 =>1001 | 1010 | 1011 | 1101

=>9 | A | B | D

=>9ABD16

0xbfa8420c =>1011 1111 1010 1000 0100 0010 1100

Whatever this number is in decimal is what position in memory that variable resides. Remember you have 2GB memory (2billion)

Hex Addition

13 May 2013 CPSC1620 71

A8B6 + B31C ---------

0 - 0 1 - 1 2 - 2 ..... 9 9 10- A 11- B 12- C 13- D 14- E 15- F 16- 10 17- 11 18- 12 19- 13 20- 14 21- 15 22- 16 23- 17 24- 18 25- 19 26- 1A 27- 1B 28- 1C 29- 1D 30- 1E 31- 1F 32- 20

2

1

D B 14

FEFE + A1DC ---------

A

1

D

1

0

1

1A

Hex Subtraction

E1B6 - B31C ---------

A1DC + A0EF ---------

A 22

A 9

D 17

E 2

C 28

D

0 28

E 00


Recommended