+ All Categories
Home > Documents > Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared...

Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared...

Date post: 03-Jan-2016
Category:
Upload: melanie-craig
View: 228 times
Download: 4 times
Share this document with a friend
Popular Tags:
220
Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year 1
Transcript
Page 1: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Computer Programming(4800153-3)

Department of Computer SciencePreparatory Year

1433/1434

Prepared by Department of Computer Science, Preparatory Year 1

Page 2: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Number Systems

Prepared by Department of Computer Science, Preparatory Year 2

Page 3: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Common Number Systems

System Base Symbols

Used by humans?

Used in computers?

Decimal 10 0, 1, … 9 Yes No

Binary 2 0, 1 No Yes

Octal 8 0, 1, … 7 No No

Hexa-decimal

16 0, 1, … 9,

A, B, … F

No No

Prepared by Department of Computer Science, Preparatory Year 3

Page 4: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Quantities/Counting (1 of 3)

Decimal Binary Octal

Hexa-decimal

0 0 0 0

1 1 1 1

2 10 2 2

3 11 3 3

4 100 4 4

5 101 5 5

6 110 6 6

7 111 7 7

Prepared by Department of Computer Science, Preparatory Year 4

Page 5: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Quantities/Counting (2 of 3)

Decimal Binary Octal

Hexa-decimal

8 1000 10 8

9 1001 11 9

10 1010 12 A

11 1011 13 B

12 1100 14 C

13 1101 15 D

14 1110 16 E

15 1111 17 F

Prepared by Department of Computer Science, Preparatory Year 5

Page 6: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Quantities/Counting (3 of 3)

Decimal Binary Octal

Hexa-decimal

16 10000 20 10

17 10001 21 11

18 10010 22 12

19 10011 23 13

20 10100 24 14

21 10101 25 15

22 10110 26 16

23 10111 27 17 Etc.

Prepared by Department of Computer Science, Preparatory Year 6

Page 7: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Conversion Among Bases

• The possibilities:

Hexadecimal

Decimal Octal

Binary

Prepared by Department of Computer Science, Preparatory Year 7

Page 8: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Quick Example

2510 = 110012 = 318 = 1916

Base

Prepared by Department of Computer Science, Preparatory Year 8

Page 9: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

12510 => 5 x 100 = 52 x 101 = 201 x 102 = 100

125

Base

Weight

Decimal System

Prepared by Department of Computer Science, Preparatory Year 9

Page 10: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Binary to Decimal

• Technique– Multiply each bit by 2n, where n is the “weight”

of the bit– The weight is the position of the bit, starting

from 0 on the right– Add the results

Prepared by Department of Computer Science, Preparatory Year 10

Page 11: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example

1010112 => 1 x 20 = 11 x 21 = 20 x 22 = 01 x 23 = 80 x 24 = 01 x 25 = 32

4310

Bit “0”

Prepared by Department of Computer Science, Preparatory Year 11

Page 12: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Octal to Decimal

• Technique– Multiply each bit by 8n, where n is the “weight”

of the bit– The weight is the position of the bit, starting

from 0 on the right– Add the results

Prepared by Department of Computer Science, Preparatory Year 12

Page 13: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example

7248 => 4 x 80 = 42 x 81 = 167 x 82 = 448

46810

Prepared by Department of Computer Science, Preparatory Year 13

Page 14: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Hexadecimal to Decimal

• Technique– Multiply each bit by 16n, where n is the “weight”

of the bit– The weight is the position of the bit, starting

from 0 on the right– Add the results

Prepared by Department of Computer Science, Preparatory Year 14

Page 15: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example

ABC16 => C x 160 = 12 x 1 = 12 B x 161 = 11 x 16 = 176 A x 162 = 10 x 256 = 2560

274810

Prepared by Department of Computer Science, Preparatory Year 15

Page 16: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Decimal to Binary

• Technique– Divide by two, keep track of the remainder– First remainder is bit 0 (LSB, least-significant bit)– Second remainder is bit 1– Etc.

Prepared by Department of Computer Science, Preparatory Year 16

Page 17: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example12510 = ?2

2 125 62 12 31 02 15 12 7 12 3 12 1 12 0 1

12510 = 11111012

Prepared by Department of Computer Science, Preparatory Year 17

Page 18: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Octal to Binary

• Technique– Convert each octal digit to a 3-bit equivalent

binary representation

Prepared by Department of Computer Science, Preparatory Year 18

Page 19: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example7058 = ?2

7 0 5

111 000 101

7058 = 1110001012

Prepared by Department of Computer Science, Preparatory Year 19

Page 20: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Hexadecimal to Binary

• Technique– Convert each hexadecimal digit to a 4-bit

equivalent binary representation

Prepared by Department of Computer Science, Preparatory Year 20

Page 21: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example10AF16 = ?2

1 0 A F

0001 0000 1010 1111

10AF16 = 00010000101011112

Prepared by Department of Computer Science, Preparatory Year 21

Page 22: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Decimal to Octal

• Technique– Divide by 8– Keep track of the remainder

Prepared by Department of Computer Science, Preparatory Year 22

Page 23: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example123410 = ?8

8 1234 154 28 19 28 2 38 0 2

123410 = 23228

Prepared by Department of Computer Science, Preparatory Year 23

Page 24: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Decimal to Hexadecimal

• Technique– Divide by 16– Keep track of the remainder

Prepared by Department of Computer Science, Preparatory Year 24

Page 25: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example123410 = ?16

123410 = 4D216

16 1234 77 216 4 13 = D16 0 4

Prepared by Department of Computer Science, Preparatory Year 25

Page 26: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Binary to Octal

• Technique– Group bits in threes, starting on right– Convert to octal digits

Prepared by Department of Computer Science, Preparatory Year 26

Page 27: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example10110101112 = ?8

1 011 010 111

1 3 2 7

10110101112 = 13278

Prepared by Department of Computer Science, Preparatory Year 27

Page 28: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Binary to Hexadecimal

• Technique– Group bits in fours, starting on right– Convert to hexadecimal digits

Prepared by Department of Computer Science, Preparatory Year 28

Page 29: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example10101110112 = ?16

10 1011 1011

2 B B

10101110112 = 2BB16

Prepared by Department of Computer Science, Preparatory Year 29

Page 30: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Octal to Hexadecimal

• Technique– Use binary as an intermediary

Prepared by Department of Computer Science, Preparatory Year 30

Page 31: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example10768 = ?16

1 0 7 6

001 000 111 110

2 3 E

10768 = 23E16

Prepared by Department of Computer Science, Preparatory Year 31

Page 32: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Hexadecimal to Octal

• Technique– Use binary as an intermediary

Prepared by Department of Computer Science, Preparatory Year 32

Page 33: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example1F0C16 = ?8

1 F 0 C

0001 1111 0000 1100

1 7 4 1 4

1F0C16 = 174148

Prepared by Department of Computer Science, Preparatory Year 33

Page 34: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Exercise – Convert …

Decimal Binary Octal

Hexa-decimal

33 100001 41 21

117 1110101 165 75

451 111000011 703 1C3

431 110101111 657 1AF

Prepared by Department of Computer Science, Preparatory Year 34

Page 35: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Binary Addition (1 of 2)

• Two 1-bit values

A B A + B

0 0 0

0 1 1

1 0 1

1 1 10“two”

Prepared by Department of Computer Science, Preparatory Year 35

Page 36: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Binary Addition (2 of 2)

• Two n-bit values– Add individual bits– Propagate carries– E.g.,

10101 21+ 11001 + 25 101110 46

11

Prepared by Department of Computer Science, Preparatory Year 36

Page 37: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Multiplication (1 of 2)

• Binary, two 1-bit values

A B A B

0 0 0

0 1 0

1 0 0

1 1 1

Prepared by Department of Computer Science, Preparatory Year 37

Page 38: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Multiplication (2 of 2)

• Binary, two n-bit values– As with decimal values– E.g., 1110

x 1011 1110 1110 0000 111010011010

Prepared by Department of Computer Science, Preparatory Year 38

Page 39: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Digital Logic

Prepared by Department of Computer Science, Preparatory Year 39

Page 40: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Introduction to Digital Logic Basics• Hardware consists of a few simple building

blocks– These are called logic gates

• AND, OR, NOT, … • NAND, NOR, XOR, …

• Logic gates are built using transistors• NOT gate can be implemented by a single transistor• AND gate requires 3 transistors

• Transistors are the fundamental devices• Pentium consists of 3 million transistors• Compaq Alpha consists of 9 million transistors• Now we can build chips with more than 100 million

transistors

Prepared by Department of Computer Science, Preparatory Year 40

Page 41: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Basic Concepts• Simple gates

– AND– OR– NOT

• Functionality can be expressed by a truth table– A truth table lists output for

each possible input combination

• Precedence– NOT > AND > OR– F = A B + A B

= (A (B)) + ((A) B)Prepared by Department of Computer

Science, Preparatory Year 41

Page 42: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Basic Concepts (cont.)• Additional useful gates

– NAND– NOR– XOR

• NAND = AND + NOT• NOR = OR + NOT• XOR implements

exclusive-OR function• NAND and NOR gates

require only 2 transistors– AND and OR need 3

transistors!

Prepared by Department of Computer Science, Preparatory Year 42

Page 43: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Basic Concepts (cont.)

• Number of functions– With N logical variables, we can define

22N functions

– Some of them are useful• AND, NAND, NOR, XOR, …

– Some are not useful:• Output is always 1• Output is always 0

– “Number of functions” definition is useful in proving completeness property

Prepared by Department of Computer Science, Preparatory Year 43

Page 44: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Basic Concepts (cont.)• Complete sets

– A set of gates is complete• If we can implement any logical function using only

the type of gates in the set– You can uses as many gates as you want

– Some example complete sets• {AND, OR, NOT} Not a minimal complete

set• {AND, NOT}• {OR, NOT}• {NAND}• {NOR}

– Minimal complete set– A complete set with no redundant elements.

Prepared by Department of Computer Science, Preparatory Year 44

Page 45: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Basic Concepts (cont.)

• Proving NAND gate is universal

Prepared by Department of Computer Science, Preparatory Year 45

Page 46: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Basic Concepts (cont.)

• Proving NOR gate is universal

Prepared by Department of Computer Science, Preparatory Year 46

Page 47: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logic Chips (cont.)

Prepared by Department of Computer Science, Preparatory Year 47

Page 48: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logic Chips (cont.)• Integration levels

– SSI (small scale integration)• Introduced in late 1960s• 1-10 gates (previous examples)

– MSI (medium scale integration)• Introduced in late 1960s• 10-100 gates

– LSI (large scale integration)• Introduced in early 1970s• 100-10,000 gates

– VLSI (very large scale integration)• Introduced in late 1970s• More than 10,000 gates

Prepared by Department of Computer Science, Preparatory Year 48

Page 49: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logic Functions

• Logical functions can be expressed in several ways:– Truth table– Logical expressions– Graphical form

• Example:– Majority function

• Output is one whenever majority of inputs is 1• We use 3-input majority function

Prepared by Department of Computer Science, Preparatory Year 49

Page 50: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logic Functions (cont.)3-input majority function

A B C F

0 0 0 00 0 1 00 1 0 00 1 1 11 0 0 01 0 1 11 1 0 11 1 1 1

• Logical expression form

F = A B + B C + A C

Prepared by Department of Computer Science, Preparatory Year 50

Page 51: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logical Equivalence

• All three circuits implement F = A B function

Prepared by Department of Computer Science, Preparatory Year 51

Page 52: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logical Equivalence (cont.)

• Proving logical equivalence of two circuits– Derive the logical expression for the output of

each circuit– Show that these two expressions are equivalent

• Two ways:– You can use the truth table method

» For every combination of inputs, if both expressions yield the same output, they are equivalent

» Good for logical expressions with small number of variables

– You can also use algebraic manipulation» Need Boolean identities

Prepared by Department of Computer Science, Preparatory Year 52

Page 53: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logical Equivalence (cont.)

• Derivation of logical expression from a circuit– Trace from the input to output

• Write down intermediate logical expressions along the path

Prepared by Department of Computer Science, Preparatory Year 53

Page 54: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logical Equivalence (cont.)

• Proving logical equivalence: Truth table method

A B F1 = A B F3 = (A + B) (A + B) (A + B)

0 0 0 00 1 0 01 0 0 01 1 1 1

Prepared by Department of Computer Science, Preparatory Year 54

Page 55: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Boolean Algebra

Prepared by Department of Computer Science, Preparatory Year 55

Page 56: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Boolean Algebra (cont.)

Prepared by Department of Computer Science, Preparatory Year 56

Page 57: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Boolean Algebra (cont.)

• Proving logical equivalence: Boolean algebra method– To prove that two logical functions F1 and F2

are equivalent• Start with one function and apply Boolean laws to

derive the other function• Needs intuition as to which laws should be applied

and when– Practice helps

• Sometimes it may be convenient to reduce both functions to the same expression

– Example: F1= A B and F3 are equivalent

Prepared by Department of Computer Science, Preparatory Year 57

Page 58: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logic Circuit Design Process

• A simple logic design process involves– Problem specification– Truth table derivation– Derivation of logical expression– Simplification of logical expression– Implementation

Prepared by Department of Computer Science, Preparatory Year 58

Page 59: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Deriving Logical Expressions

• Derivation of logical expressions from truth tables– sum-of-products (SOP) form– product-of-sums (POS) form

• SOP form – Write an AND term for each input combination

that produces a 1 output• Write the variable if its value is 1; complement otherwise

– OR the AND terms to get the final expression

• POS form– Dual of the SOP form

Prepared by Department of Computer Science, Preparatory Year 59

Page 60: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Deriving Logical Expressions (cont.)

• 3-input majority function

A B C F

0 0 0 00 0 1 00 1 0 00 1 1 11 0 0 01 0 1 11 1 0 11 1 1 1

• SOP logical expression• Four product terms

– Because there are 4 rows with a 1 output

F = A B C + A B C + A B C + A B C

Prepared by Department of Computer Science, Preparatory Year 60

Page 61: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Deriving Logical Expressions (cont.)

• 3-input majority function

A B C F

0 0 0 00 0 1 00 1 0 00 1 1 11 0 0 01 0 1 11 1 0 11 1 1 1

• POS logical expression• Four sum terms

– Because there are 4 rows with a 0 output

F = (A + B + C) (A + B + C) (A + B + C) (A + B + C)

Prepared by Department of Computer Science, Preparatory Year 61

Page 62: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logical Expression Simplification• Two basic methods

– Algebraic manipulation• Use Boolean laws to simplify the expression

– Difficult to use– Don’t know if you have the simplified form

– Karnaugh map (K-map) method• Graphical method• Easy to use

– Can be used to simplify logical expressions with a few variables

Prepared by Department of Computer Science, Preparatory Year 62

Page 63: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Algebraic Manipulation• Majority function example

A B C + A B C + A B C + A B C =

A B C + A B C + A B C + A B C + A B C + A B C

• We can now simplify this expression as

B C + A C + A B

• A difficult method to use for complex expressions

Added extra

Prepared by Department of Computer Science, Preparatory Year 63

Page 64: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Implementation Using NAND Gates

• Using NAND gates– Get an equivalent expression

A B + C D = A B + C D– Using de Morgan’s law

A B + C D = A B . C D– Can be generalized

• Majority function

A B + B C + AC = A B . BC . AC

Prepared by Department of Computer Science, Preparatory Year 64

Page 65: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Implementation Using NAND Gates (cont.)

• Majority function

Prepared by Department of Computer Science, Preparatory Year 65

Page 66: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logical Expression Simplification

Prove the following Equivalence:

Prepared by Department of Computer Science, Preparatory Year 66

Page 67: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logical Expression Simplification

• Prove that 1.X.(Y+Z) = X.Y + X.Z 2.X+XY = X3. X(X+Y) = X

Prepared by Department of Computer Science, Preparatory Year 67

Page 68: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Logical Expression Simplification

• Simplify the next:

Prepared by Department of Computer Science, Preparatory Year 68

Page 69: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Algorithms and Flowcharts

Prepared by Department of Computer Science, Preparatory Year 69

Page 70: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Problem Solving in a Computer System

• The main purpose of problem solving is to convert inputs to outputs with some processes.

Prepared by Department of Computer Science, Preparatory Year 70

Page 71: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Main Steps in Problem Solving in Computer System - Problem understanding

- Algorithm developing

- Program writing

- Program editing

- Program compiling

- Program running

- Testing and debugging

71Prepared by Department of Computer Science, Preparatory Year

Page 72: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Main Operations for Problem Solving

• Input operations:– Like: input, read

• Output operations;– Like: write, print

• Arithmetic operations:– Like: add, subtract, multiply etc....

• control transferring operations:– Like: conditional, non-conditional etc....

• Looping:– Like: repeat, do while, for, etc...

Prepared by Department of Computer Science, Preparatory Year 72

Page 73: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

What is an Algorithm?

“A sequence of precise instructions which leads to a solution is called an algorithm.”

or“An algorithm is a set of steps that defines how a task is to performed.”Example:

Steps (algorithm) to solve a first degree equation.Steps (algorithm) to calculate the area of TriangleSteps (algorithm) to find maximum digits among a set

of input digits

Prepared by Department of Computer Science, Preparatory Year 73

Page 74: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

What is the algorithm for solving a first degree equation (AX = B)?

1. Read the values A,B

2. Check if A=0 (if yes there is no equation) therefore no equation to be solved (end processing).

3. Check if B=0 (if yes X=0 and end processing).

4. Calculate the value of X= B/A

5. Print the value of : X

Example:

74Prepared by Department of Computer Science, Preparatory Year

Page 75: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Algorithm Representation

There are many ways in which we may represent an algorithm.

We use many techniques to represent an algorithm in computer programming, such as:

Flowchart Pseudocde

75Prepared by Department of Computer Science, Preparatory Year

Page 76: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Why Flowcharts:

The flowchart is graphical representation of the steps required for an algorithm or program.

The flowchart is characterized by:

Clarify the program logic

Identify alternative processing methods

Serve as guide for program coding

Serve as documentation

76Prepared by Department of Computer Science, Preparatory Year

Page 77: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Principals of Flowchart

1. Simplicity:- Easy to put on paper- Easy to draw- Readable and meaningful

2. Organization:- putting ideas together and organizing those ideas in

logical way.3. Planning:

- flowchart helps for looking the program in deeper and global way.

77Prepared by Department of Computer Science, Preparatory Year

Page 78: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

General Concepts

Flowchart must be characterized by the following:1. The major element of the project.

2. Elements are clearly labeled.

3. Sequence of element must be clear.

4. No gap or dead ends.

5. Sequence of elements must be in logical form.

6. Flowchart must be used correctly.

78Prepared by Department of Computer Science, Preparatory Year

Page 79: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

1. Simple sequential flowchart.

2. Branched flowchart.

3. Simple-loop flowchart.

4. Multi-loop flowchart.

Levels of Flowcharts

79Prepared by Department of Computer Science, Preparatory Year

Page 80: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

No Name Symbol Usage

1 Ellipse Start/Stop

2 Rectangle Expressions

3 Parallelogram

Input (Read) / Output(Print)

4 Rhombus Conditional checking

5 Arrow Flow of solution

6 Circle Connector

7 Elongated Hexagon Continue

8 Rectangle with bars

Procedure / Function call80Prepared by Department of Computer

Science, Preparatory Year

Page 81: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

First Level of Flowchart

It is simplest level which contain the sequence of steps without loops or branch and the flowchart comes in straight line from the beginning to the end.

81Prepared by Department of Computer Science, Preparatory Year

start

Stop

process 1...

Process n

Page 82: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Second Level of Flowchart

It is branched flowchart, when there is a condition statement in the program.

82Prepared by Department of Computer Science, Preparatory Year

start

Input

Stop

Process 1--n

Condition?

Yes No

Process 1--m

Page 83: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Third Level of Flowchart

It is a flowchart which contain iteration or repetitions. It is usually called loop flowcharts.

In this type we need to repeat some operation several times using the same set of operation.

The general form for this type is as follow:

83Prepared by Department of Computer Science, Preparatory Year

Page 84: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example 1: Algorithm for reading student name

1. Start

2. Read student name

3. End

start

Read student name

Stop

84Prepared by Department of Computer Science, Preparatory Year

Page 85: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example 2: Algorithm for calculate the area of circle

1. Start

2. Read value of R

3. Set PI equal to 3.14

4. Calculate Area=PI*R*R

5. Print R, Area

6. Stop

start

Read R

Stop

PI=3.14

Area=Pi*R*R

Print R, Area

85Prepared by Department of Computer Science, Preparatory Year

Page 86: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example 3: Write an algorithm and draw the flowchart to add two numbers.

Algorithm:

1.Start

2.Read a, b

3.Calculate c = a + b

4.Print c

5.Stop

Flow chart:

Start

c = a+ b

Print c

Read a, b

Stop

86Prepared by Department of Computer Science, Preparatory Year

Page 87: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example 4: Write an algorithm and draw a flowchart to find the circumference of circle

Algorithm:1.Start

2.Read r

3.Calculate c = 2*3.14 * r

4.Print c

5.Stop

87Prepared by Department of Computer Science, Preparatory Year

Page 88: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example 5: Draw a flowchart to evaluate the following functions: F(X)=x if X>=0, F(X)= -X if X<0

1. Start

2. Read X

3. If X>=0 then go to step 4, else step 5

4. Calculate F(X)=X than go to step 6

5. Calculate F(X)=X

6. Print X, F(X)

7. Stop

start

Read X

Stop

F(X)= -X

Print X, F(X)

X>=0

F(X)=X

A

Yes

No

88Prepared by Department of Computer Science, Preparatory Year

Page 89: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example 6: write an algorithm and draw a flowchart to print 10 integers starting from 1Algorithm:1.Start

2.Set A=1

3.Check if A<=10 if yes goto step 4 else got to step 7

4. Print A

5.Calculate A = A+1

6.Goto step 3

7. If no End

89Prepared by Department of Computer Science, Preparatory Year

Page 90: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Exercise

Write an algorithm and draw the flowchart that read three numbers and print the value of the largest number.

Prepared by Department of Computer Science, Preparatory Year 90

Page 91: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

ExerciseStep 1: Input N1, N2, N3Step 2: if (N1>N2) then

if (N1>N3) then MAX N1 [N1>N2, N1>N3]

else MAX N3 [N3>N1>N2]

endifelse

if (N2>N3) then MAX N2 [N2>N1, N2>N3]

else MAX N3 [N3>N2>N1]

endifendif

Step 3: Print “The largest number is”, MAX

Prepared by Department of Computer Science, Preparatory Year 91

Page 92: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Looping

• When we need to use a loop a special symbol can be used

1. Counter i2. Any Initial value ( Set i =0) 3. Final Value (N) (Set N= 10)4. Increment or Decrement Value (M)(Set M=1)

Loopi = 0,N,M

Instructions to be executed

M

92Prepared by Department of Computer Science, Preparatory Year

Page 93: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Exercise

• Write an algorithm and draw a flowchart to calculate and print the sum of numbers from 1 to 10 .

93Prepared by Department of Computer Science, Preparatory Year

Page 94: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Programming Using C++

Introduction

Prepared by Department of Computer Science, Preparatory Year 94

Page 95: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Programming Language

• Programming language is an artificial language that specifies instruction to be executed on a computer.

• This language consists of a set of commands, understandable by computer directly or after

translating.

Prepared by Department of Computer Science, Preparatory Year 95

Page 96: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Computer Languages:

• There are many types of computer languages, which can be categorized into the following four types:-

a) Low-Level Languages (1st & 2nd Generation Languages)b) High-Level Languages (3rd Generation Languages)c) User-Friendly Languages (4th Generation Languages)d) Object-Oriented Languages (5th Generation Languages)

Prepared by Department of Computer Science, Preparatory Year 96

Page 97: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Computer Languages:

A. Low Level Language (Machine):– A language that is machine-dependent and/or that offers

few control instructions and data types. – Each statement in a program written in a low-level

language usually corresponds to one machine instruction.– To calculate Area = Width * Length in Low Level

language:

100100 010001 //Load

100110 010010 //Multiply100010 010011 //Store

Prepared by Department of Computer Science, Preparatory Year 97

Page 98: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Computer Languages:

b. High-Level Language:– The languages, which computer cannot

understand directly and are not machine dependent are called High-Level Languages. Some of the high-level languages are:-

• BASIC (Beginners All Purpose Symbolic Instruction Code)

• COBOL (Common Business Oriented Language)• FORTRAN (Formula Translator)• C

Prepared by Department of Computer Science, Preparatory Year 98

Page 99: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Computer Languages:

c. User-Friendly Languages:– These languages are very easy to codify and

simplest to learn. Some of the common user-friendly languages are:-

• dBASE• FoxPro• Oracle• Sybase

Prepared by Department of Computer Science, Preparatory Year 99

Page 100: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Computer Languages:

d. Object-Oriented Languages:– The languages which are based on object

oriented programming (OOP) approach are called as Object-Oriented languages. For example:-

• Smalltalk• C++• Object COBOL• JAVA• Simula

Prepared by Department of Computer Science, Preparatory Year 100

Page 101: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Language Translators:

• The software, which converts the codes of other languages into machine code are called Language Translator.

• Language Translators are categorized into three types:-– Assemblers– Interpreters– Compilers

Prepared by Department of Computer Science, Preparatory Year 101

Page 102: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Language Translators:

1) Assembler:• Assembler translates the assembly language code

(source program) into machine language code (object program).

• After assembling, a linker program is used to convert the object program into an executable program.

• The Microsoft assembler program (MASM) • Borland Turbo assembler program (TASM)

• Assemblers are used mainly in development of system software.

Prepared by Department of Computer Science, Preparatory Year 102

Page 103: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Language Translators:

2) Interpreters:• Interpreters translate the high-level language

code into machine language code, command by command.

• They are very slow for executing large programs.

Prepared by Department of Computer Science, Preparatory Year 103

Page 104: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Language Translators:3) Compilers:• As contrast to interpreters, compilers provide faster

execution speed. • Compilers translate the entire program (source code)

into machine code (Object File). By using linker, the object code is converted into Executable File.

• Compilers are widely used in translating codes of high level languages.

• As compared to assemblers or interpreters, compilers are preferred in development of application software.

Prepared by Department of Computer Science, Preparatory Year

Compiler Source File Object File Linker Excutable File

104

Page 105: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Debugging

• Programming errors are called bugs • Debugging - the process of tracking them

down.• Three kinds of errors:

– syntax errors– runtime errors– semantic errors

105Prepared by Department of Computer Science, Preparatory Year

Page 106: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Syntax errors

• Occur if syntax is not correct• Syntax refers to the structure of a program

and the rules about that structure. • (1 + 2) is legal• 8) is a syntax error

106Prepared by Department of Computer Science, Preparatory Year

Page 107: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Runtime errors

• Error does not appear until after the program has started running

• Also called exceptions • Rare in simple programs

107Prepared by Department of Computer Science, Preparatory Year

Page 108: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Semantic errors

• Program runs successfully (no error messages generated)

• Will not do the right thing• The program result is wrong.• Tricky to identify

108Prepared by Department of Computer Science, Preparatory Year

Page 109: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Motivation for Studying C++

• The objective of learning C++ is to write programs using this higher level language to solve our day-to-day problems and tomorrow may be to write a whole software. It is a most widely used language.

Prepared by Department of Computer Science, Preparatory Year 109

Page 110: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Origins of C++

• The first language developed was (BCPL) and the next upgraded version was (B). the language (B) was upgraded to (C) by Dennis Ritche of AT & T laboratories, USA.{ C was first used to write UNIX OS }

• (C)is a general purpose language.• Bjarne Strousstrup added object orientation

to (C )and developed (C++)

Prepared by Department of Computer Science, Preparatory Year 110

Page 111: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

A Simple C++ Program

Let us begin with a simple C++ program that displays the message “Welcome to C++!” .

#include <iostream>using namespace std;void main(){

// Display Welcome to C++ cout << "Welcome to C++!" << endl;}

Prepared by Department of Computer Science, Preparatory Year 111

Page 112: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Extending the Simple C++ Program

Once you understand the program, it is easy to extend it to display more messages. For example, you can rewrite the program to display three messages.

#include <iostream>using namespace std;void main(){ cout << "Programming is Useful!" << endl;

cout << "Fundamentals First" << endl;cout << "Problem Driven" << endl;

}

Prepared by Department of Computer Science, Preparatory Year 112

Page 113: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Computing with Numbers

Further, you can perform mathematical computations and displays the result .

#include <iostream>using namespace std;void main(){ cout << (1 + 2 + 3) / 3 << endl;}

Prepared by Department of Computer Science, Preparatory Year 113

Page 114: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Basic Concepts for Programming Skills

Programming Using C++

Prepared by Department of Computer Science, Preparatory Year 114

Page 115: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Phase of C++ Programs

1) EditProgram is created in the editor and stored on the disk 2) CompileCompiler create Object code and stores on disk3) LinkLinker links the Object code with Libraries, creates result and

stores it on disk4) LoadLoader prints program in memory5) ExecuteCPU takes each instruction and executes it. Possibly storing new

data Values as program executePrepared by Department of Computer Science, Preparatory Year 115

Page 116: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Creating, Compiling, and Running Programs

Source Code

Create/Modify Source Code

Compiler

Executable Code

Run Executable Code e.g., Welcome

Result

If compilation errors

If runtime errors or incorrect result

#include <iostream> using namespace std; int main() { // Display Welcome to C++ to the console cout << "Welcome to C++!" << endl; return 0; }

Saved on the disk

stored on the disk

Source code (developed by the programmer)

Machine Code program

Linker

stored on the disk

An object file (e.g., Welcome.obj) is created.

An executable file (e.g., Welcome.exe) is created.

Prepared by Department of Computer Science, Preparatory Year 116

Page 117: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

C++ Character Set

• Character set includes the basic building blocks of a language.

• C++ character set consists of:a) Numeric Character Set: 0-9b) Alphabetic Character Set: A-Z, a-zc) Special Character Set: # , ; , :,(comma) etcd) Escape Character Set: they are used for formatting the

output. • It always starts with a back slash ( \ ). • Some Examples are \n, \t, \b, \a

Prepared by Department of Computer Science, Preparatory Year 117

Page 118: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Tokens

• The smallest individual unit in a program is known as token.

• C++ has the tokens, like:Keywords, Identifiers, Literals, Punctuators, Operators

Prepared by Department of Computer Science, Preparatory Year 118

Page 119: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Keywords

• Reserved words or Keywords are those words which are reserved for a specific purpose and part of the language.

Examples are:if, int, char, break, constant, case, do, class, else,template, true, structure, void etc

Prepared by Department of Computer Science, Preparatory Year 119

Page 120: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Identifiers• Words that are not reserved or keywords are

called user defined words or identifiers. • Identifiers must follow the following rules:

a) Can be composed of alphabets (A-Z or a-z), numbers (0 to 9) and underscore “_”

b) The first character must be an alphabet or an underscore “_”.

c) Identifier must be unique.d) Blank Spaces are not allowed.e) They are case sensitive i.e. Val and val are different

Examples: Roll_number, r_no, Z, A1234_BC etc.• Use the name of the identifier that is self explanatory e.g. employee_name, student_name etc.

Prepared by Department of Computer Science, Preparatory Year 120

Page 121: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Data Types– Data types are means to identify the type

of data and associated operations of handling it.

–C++ data types are of two types:(i) Fundamental data types

(ii) Derived data type

Prepared by Department of Computer Science, Preparatory Year 121

Page 122: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Data Types(i) Fundamental Data Types

Name Data type Size in bytes

Range of values

char Character 1-Byte -128 to 127int Integer 2-Bytes -32768 to 32767short int Short Integer 2-Bytes -32768 to 32767long int Long Integer 4-Bytes -2147483648 to

2147483647float Floating Point 4-Bytes -3.4E+38 to 3.4E+38double Double Floating Point 8-Bytes -1.7E+308 to

1.7E+308

Prepared by Department of Computer Science, Preparatory Year 122

Page 123: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Data Types(ii) Derived data type– From the fundamental types other types can be

derived by using the declaration operators, e.g. Arrays.

• Expression:

– Expressions are the valid combination of operators, constants and or variables.

e.g. X = X + 5;

Prepared by Department of Computer Science, Preparatory Year 123

Page 124: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Constants and Variables• Identifiers can be classified into two categories

constants and variables.

1. Constants (Literals)– Constants are identifiers which do not change its

stored value during executing the program.– Two types are:

(a) Numeric Constant e.g. const float pi=3.14;(b) Non Numeric constant e.g. const char pi=’Π’;

Prepared by Department of Computer Science, Preparatory Year 124

Page 125: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Constants and Variables2. Variables

– a variable is an identifier that has a changeable value during the execution of a program.

– Variable Declaration:• Declare a variable means to allocate a memory location to

hold the value of this variable.• To define a variable, each variable should have:

Identifier: which is the variable name that you will use during the program, and in fact it is translated to an address of the memory location.

Data Type: which shows the type of the value that will be stored in this variable. Example

Data_Type Identifier;int number1;

Prepared by Department of Computer Science, Preparatory Year 125

Page 126: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Constants and Variables• There are different types of variables such as:-

(a) Character variable (To store characters)(b) Integer variable (To store whole numbers)(c) Float variable (To store floating point numbers)(d) Boolean variable (To store two values true/false)

e.g. int a,b,c,d=10; (you can also initialize at the time of declaration)

Prepared by Department of Computer Science, Preparatory Year 126

Page 127: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Punctuators• The following characters are used as

punctuators (also known as separators) in C++.[ ] ( ) { } , ; : * … = #

Prepared by Department of Computer Science, Preparatory Year 127

Page 128: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Operators cause the compilers to take some action.• Operators work on operands (data). • Operators are classified as:-

• I/O operators:• input operator(>>) is used to read value from standard input• output operator(<<) is used to direct a value to standard output.

• Assignment Operator:• Equal sign (=) : used for assignment operator. It is used to assign

values to variables e.g. A=10 or a=b. In every case the value of the right hand variable (constant) are assigned to variable in the left hand side.

Prepared by Department of Computer Science, Preparatory Year 128

Page 129: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Assignment Operator:

Example 1:int x;float y=12.52;x=y;cout<<”value of x= ”<<x;

//the output is 12 as x is an integer it is truncated to 12

Example 2:int x=11;float y=x;cout<<”value of y= ”<<y;

//the output is 11.0 as y is a float variable its value becomes 11.0

Prepared by Department of Computer Science, Preparatory Year 129

Page 130: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Arithmetic Operators:

– Are used to perform arithmetic operations. For Example:

– These used to perform arithmetic operations. There are always two operands e.g. in a + b OR (Operand1 + Operand2) a and b are operands.

Addition +Subtraction -Division /Multiplication *Used to find out remainder %

Prepared by Department of Computer Science, Preparatory Year 130

Page 131: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Arithmetic Operators:

– They can be of any data types.

Operand-1 (a) Operand-2 (b) Operations Result

int int +, -, *, / intint float +, -, *, / floatfloat int +, -, *, / floatfloat float +, -, *, / floatfloat double +, -, *, / doubleLong double double +, -, *, / Long double

Prepared by Department of Computer Science, Preparatory Year 131

Page 132: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Arithmetic Operators:

– Note that the result always takes the larger data type of the operands used.

Example 1: int x=10, y=3;cout<<”value of x= ”<<x/y;

//the output is 3 not 3.33 as both the operands are integers

Example 2: int x=10;float y=3.5;cout<<”value of x= ”<<x/y;

//the output is 3 not 3.33 as both the operands are integers

Prepared by Department of Computer Science, Preparatory Year 132

Page 133: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Unary operators :

– Increment (++) e.g. a++ (postfix), ++a(prefix) equivalent to a=a+1

– Decrement (--) e.g. b-- (postfix), --b (prefix) equivalent to b=b-1

– When these operators (prefix or suffix) are used in isolation, their impact is same

e.g. if a=10, a++ or ++a results making a=11. But the impacts are different when used along with

assignment operators or cout statements

Prepared by Department of Computer Science, Preparatory Year 133

Page 134: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Unary operators : Examples

void main( ){ int x=10;x++;cout << x;} //output is 11 as x++ is x=x+1

void main( ){ int x=10;++ x;cout << x;} //output is 11 as ++x is also x=x+1

void main( ){ int x=10;cout << x++;} //output is 10 as it outputs thenincrements

void main( ){ int x=10;cout << ++x;} //output is 11 as it increments thenoutputs

Prepared by Department of Computer Science, Preparatory Year 134

Page 135: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Unary operators : Find the output for the following

void main( ){ int x=10,y;y= --x+y;cout << x<<’\t’<<y;}

void main( ){ int x=10,y;y= x-- + y;cout << x<<’\t’<<y;}

void main( ){ int x=10,y=5;y= --x* ++y;cout << x<<’\t’<<y;}

void main( ){ int x=10,y=5;y= --x* y++;cout << x<<’\t’<<y;}

Prepared by Department of Computer Science, Preparatory Year 135

Page 136: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Relational Operators:

– are used for the comparison of variables. For Example:

Less than <Greater than >Less than or equal to <=Greater than or equal to >=Equal to ==Not equal to !=

Prepared by Department of Computer Science, Preparatory Year 136

Page 137: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Relational Operators:

• For Example:

– Remaining operators work in the same way.

(X<Y) If X is less than Y the condition results to true otherwise results to false

(X<=Y) If X is less than or equal to Y the condition results to true otherwise results to false

Prepared by Department of Computer Science, Preparatory Year 137

Page 138: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Logical Operators:

– are used to for logical combination, disjunction or negation of variables.

In general Symbol in program Use Explanation

AND && a&&b True if a is true and b is true else false

OR | | a | | b True if either a is true or b is true else false

NOT ! ! a True if a is false and vice versa

Prepared by Department of Computer Science, Preparatory Year 138

Page 139: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Logical Operators:

– Examples are :1.(a>b) && (b>c) is true if (a>b) is true and (b>c) is

true2.(a>b) && (b>c) is false if one of them is false or

both are false3.(a>b) || (b>c) is true if either (a>b) is true or (b>c) is

true or both are true4.(a>b) || (b>c) is false when both are false

Prepared by Department of Computer Science, Preparatory Year 139

Page 140: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators

• Compound operators:– C++ allows the assignment to combine with other

operators.Examples: Z+=5; which is equal to Z=Z+5;

x*=y is equal to x=x*y; x/=5 is equal to x=x/y;

Prepared by Department of Computer Science, Preparatory Year 140

Page 141: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Operators• Compound operators: Find out for the output for following

void main( ){ int x=10,y=20; y*= x; x+=y; cout << x<<’\t’<<y;}

void main( ){ int x=10,y=30; y/= x; x=y++; cout << x<<’\t’<<y;}

void main( ){ int x=10,y=40; y+= x; cout << x<<’\t’<<y;}

void main( ){ int x=10,y=40; y*= x; x=x++; cout << x<<’\t’<<y;}

Prepared by Department of Computer Science, Preparatory Year 141

Page 142: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

The Priority of Operators

Prepared by Department of Computer Science, Preparatory Year 142

Highest

Lowest

Page 143: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Input/Output

Programming Using C++

Prepared by Department of Computer Science, Preparatory Year 143

Page 144: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Input/Output in C++• cout The identifier cout is a predefined object that corresponds

to standard output stream.

• cin The identifier cin is a predefined object that corresponds

to standard input stream.

• Escape sequence/ Escape character Character combinations consisting of a backslash (\)

followed by a letter or by a combination of digits is called “escape sequence”.

Prepared by Department of Computer Science, Preparatory Year 144

Page 145: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Input/Output in C++ I/O operators

The input operator(>>) is used to read value from standard input, while output operator(<<) is used to direct a value to standard output. For Example:

#include<iostream>Using namespace std;void main( ){

int a,b,c;float d;cout<<”Enter three numbers”;cin>>a>>b>>c;d=(a+b+c)/3;cout<<”The average”<<d;

}

Prepared by Department of Computer Science, Preparatory Year 145

Page 146: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Input and Output

• A data stream is a sequence of data. Typically in the form of characters or numbers

• An input stream is data for the program to use– Usually originates from:

• the keyboard• a file

• An output stream is the program’s output– Destination would be usually :

• the monitor• a file

Prepared by Department of Computer Science, Preparatory Year 146

Page 147: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Output using cout• cout is an output stream sending data to the

monitor• The insertion operator "<<" inserts data into “cout”• Example:

cout << number_of_bars << " candy bars\n";– This line sends two items to the monitor

• The value of number_of_bars• The quoted string of characters " candy bars\n"

– Notice the space before the ‘c’ in candy– The ‘\n’ causes a new line to be started following the ‘s’ in

bars• A new insertion operator is used for each item of

outputPrepared by Department of Computer

Science, Preparatory Year 147

Page 148: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Examples Using cout• This produces the same result as the previous sample

cout << number_of_bars ; cout << " candy bars\n";

• Here arithmetic is performed in the cout statement cout << "Total cost is $" << (price + tax);Quoted strings are enclosed in double quotes ("Walter")– Don’t use two single quotes (')

• A blank space can also be inserted with cout << " " ;if there are no strings in which a space is desired as in " candy bars\n"

Prepared by Department of Computer Science, Preparatory Year 148

Page 149: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Include Directives

• Include Directives add library files to our programs

– To make the definitions of the cin and cout available to the program: #include <iostream>

• Using Directives include a collection of defined names

– To make the names cin and cout available to our program:

using namespace std;

Prepared by Department of Computer Science, Preparatory Year 149

Page 150: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Escape Sequences• Escape sequences tell the compiler to treat characters

in a special way• '\' is the escape character

– To create a newline in output use \n – cout << "\n"; or the newer alternative cout << endl;

– Other escape sequences: \t -- a tab \\ -- a backslash character \" -- a quote character

Prepared by Department of Computer Science, Preparatory Year 150

Page 151: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Input Using cin• cin is an input stream bringing data from the keyboard• The extraction operator (>>) removes data to be used• Example:

cout << "Enter the number of bars in a package\n"; cout << " and the weight in ounces of one bar.\n"; cin >> number_of_bars; cin >> one_weight;

• This code prompts the user to enter data then reads two data items from cin– The first value read is stored in number_of_bars– The second value read is stored in one_weight– Data is separated by spaces when entered

Prepared by Department of Computer Science, Preparatory Year 151

Page 152: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Reading Data From cin

• Multiple data items are separated by spaces• Data is not read until the enter key is pressed

– Allows user to make corrections• Example:

cin >> v1 >> v2 >> v3;– Requires three space separated values – User might type

34 45 12 <enter key>

Prepared by Department of Computer Science, Preparatory Year 152

Page 153: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Designing Input and Output

• Prompt the user for input that is desired– cout statements provide instructions

cout << "Enter your age: ";cin >> age;

• Notice the absence of a new line before using cin

• Echo the input by displaying what was read– Gives the user a chance to verify data

cout << age << " was entered." << endl;

Prepared by Department of Computer Science, Preparatory Year 153

Page 154: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Programming Using C++

Control Structures

Prepared by Department of Computer Science, Preparatory Year 154

Page 155: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Conditional Constructs

• Provide– Ability to control whether a list of statements is executed– A mechanism for deciding whether an action should be

taken• Two types

– If statement• if statement• if-else statement• Nested if-else structure

– Switch statement

155Prepared by Department of Computer Science, Preparatory Year

Page 156: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

The Basic If Statement• Syntax

if (Expression) Action• If the Expression is true then

execute Action• Action is either a single statement or a group of

statements within braces

Expression

Action

true

false

12Prepared by Department of Computer

Science, Preparatory Year

Page 157: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Exampleif (Value < 0){ Value = -Value;}

13Prepared by Department of Computer Science, Preparatory Year

If Value is less than zero then we need to update its value to that of its additive inverse

The number is now definitely nonnegative

If Value is not less than zero then our number is fine as is

Is the Value negative ?

Value < 0

Value = - Value

true

false

Page 158: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Sorting Two Numbers

void main(){

cout << "Enter two integers: ";int Value1;int Value2;cin >> Value1 >> Value2;if (Value1 > Value2) {

int RememberValue1 = Value1;Value1 = Value2;Value2 = RememberValue1;

}cout << "The input in sorted order: "

<< Value1 << " " << Value2 << endl;}

158Prepared by Department of Computer Science, Preparatory Year

Page 159: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

What is the Output?int m = 5;

int n = 10;

if (m < n)

++m;

++n;

cout << " m = " << m << " n = “ << n << endl;

16Prepared by Department of Computer

Science, Preparatory Year

Page 160: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

The If-Else Statement• Syntax

if (Expression) Action1else Action2

• If Expression is true then executeAction1 otherwise execute Action2

if (v == 0) {

cout << "v is 0"; }

else { cout << "v is not 0"; }

Expression

Action1 Action2

true false

17Prepared by Department of Computer Science,

Preparatory Year

Page 161: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Finding the Max

void main(){

cout << "Enter two integers: ";int Value1;int Value2;cin >> Value1 >> Value2;int Max;if (Value1 < Value2) {

Max = Value2;}else {

Max = Value1;}

cout << "Maximum of inputs is: " << Max << endl;}

161Prepared by Department of Computer Science, Preparatory Year

Page 162: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Finding the Max

162Prepared by Department of Computer Science, Preparatory Year

Yes, it is. So Value2 is larger than Value1. in this case, Max is

set to Value2

Is Value2 larger than Value1 ? No, its not. So

Value1 is at least as large as Value2. In this Case, Max is

set to Value1

Either case, Max is set correctly

Value1 < Value2

Max = Value2 Max = Value1

falsetrue

Page 163: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Selection

• It is often the case that depending upon the value of an expression we want to perform a particular action

• Two major ways of accomplishing this choice

– Nested if structure• if-else statements "glued" together

– Switch statement• An advanced construct

163Prepared by Department of Computer Science, Preparatory Year

Page 164: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

If-Else Structureif ( nbr < 0 ){cout << nbr << " is negative" << endl;

}else if ( nbr > 0 ) {cout << nbr << " is positive" << endl;

}else {cout << nbr << " is zero" << endl;

}

164Prepared by Department of Computer Science, Preparatory Year

Page 165: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Switch Statement

• A nested if-else structure is just as efficient as a switch statement.

• However, a switch statement may be easier to read.

• Also, it is easier to add new cases to a switch statement than to a nested if-else structure.

165Prepared by Department of Computer Science, Preparatory Year

Page 166: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Switch Statementswitch (expression){ case Constant1:

Action1; break;

case Constant2: Action 2; break;

. . default:

default group of Actions}

Prepared by Department of Computer Science, Preparatory Year 166

Page 167: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Break• The last statement of each case in the switch

statement should almost always be a break.• The break causes program control to jump to

the closing brace of the switch structure.• Without the break, the code flows into the

next case. This is almost never what you want.• A switch statement will compile without a

default case, but always consider using one.

167Prepared by Department of Computer Science, Preparatory Year

Page 168: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example1switch (ch) {case 'a': case 'A':case 'e': case 'E':case 'i': case 'I':case 'o': case 'O':case 'u': case 'U':

cout << ch << " is a vowel" << endl;

break;default:

cout << ch << " is not a vowel" << endl;

}168Prepared by Department of Computer Science,

Preparatory Year

Page 169: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

void main(){

cout << "Enter simple expression: ";int Left;int Right;char Operator;cin >> Left >> Operator >> Right;cout << Left << " " << Operator << " " << Right

<< " = ";switch (Operator) {

case '+' : cout << Left + Right << endl; break;case '-' : cout << Left - Right << endl; break;case '*' : cout << Left * Right << endl; break;case '/' : cout << Left / Right << endl; break;default: cout << "Illegal operation" << endl;

}}

169Prepared by Department of Computer Science, Preparatory Year

Example2

Page 170: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Programming Using C++

Repetition Structure(Loop)

Prepared by Department of Computer Science, Preparatory Year 170

Page 171: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Definition

• A Repetition structure: certain parts of the code will be executed multiple times, or not at all based on the current state (condition).

• A loop: is a group of instructions the computer executes repeatedly until a terminating condition is satisfied.

• In C++, there are 3 forms of implementing repetition:

• While Loop• Do-while Loop• For Loop

Prepared by Department of Computer Science, Preparatory Year 171

Page 172: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

While Loop

The syntax in C++ is Initialize; while (condition) {

statement; //action

increment; }

Prepared by Department of Computer Science, Preparatory Year 172

StatementsIncrement

condition

Yes

No

initialize

Page 173: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

While LoopThe syntax in C++ is Initialize; while (condition) {

statement; //action

increment; }

Prepared by Department of Computer Science, Preparatory Year 173

• Initialize: initialize the control variable which will be used to test the condition, this initialization is applied only once.

• If the condition is true, the statement and the increment are executed, then the whole thing is done again.

• The statement and the increment are executed repeatedly until the condition becomes false.

• If the condition starts out false, the while-body will never be executed.

• Increment: is the statement that makes change on the condition, otherwise, the loop will continue running. (Infinite loop).

Page 174: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

174

Trace While Loop

Trace the following code:

Void main()

{

int count = 0;

while (count < 2)

{

cout << "Welcome to C++!";

count++;

}

} Prepared by Department of Computer Science, Preparatory Year

Page 175: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Do-While Loop

The syntax in C++ is: do { …any number of statements… // action} while (condition) ;

Prepared by Department of Computer Science, Preparatory Year 175

StatementsIncrement

conditionYes

No

Page 176: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Do-While LoopThe syntax in C++ is: do { …any number of statements… // action } while (condition) ;

Prepared by Department of Computer Science, Preparatory Year 176

• The do-while statement performs the test after executing the body.

• As long as the test is true, the body will execute again.

• In all cases the body will be executed at least once, even if the condition was wrong because testing happened at the end.

• The difference between while and do-while : – The testing happen before executing the

body in the while structure, so if the condition is false from the beginning, the body will not be executed at all.

Page 177: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Do-While ExampleVoid main(){

int count = 1; do {

cout << "Welcome to C++!";

count++;

} while (count <= 2);

}

--------------------------------------------------------•What is the output?•What is the output if the condition changed to (count >=2)?

Prepared by Department of Computer Science, Preparatory Year 177

Page 178: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

For Loop• The syntax in C++ is:for ( initialize ; condition ; increment ) {

statements ; }

Prepared by Department of Computer Science, Preparatory Year 178

Page 179: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

For Loop• The syntax in C++ is:for ( initialize ; condition ; increment ) { statements ; }

Prepared by Department of Computer Science, Preparatory Year 179

for structure is composed of 4 parts:•Initialize: initialize the loop control variable, and done only once.•Condition: is the condition that determines whether the loop should continue executing or not.•Statements: the body of the loop.•The increment: is a statement that changes the value of the initialization either by adding, subtracting, or any math operation. But usually it is either adding or subtracting.

• Notice that there is no semicolon after the increment.• It is better to use for structure when the number of iterations is

known.

Page 180: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

180

For Loop Example

Try to trace the following code:

void main(){

int i;for (i = 0; i < 2; i++) {

cout << "Welcome to C++!"; }

}

Prepared by Department of Computer Science, Preparatory Year

Page 181: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Break and Continue Statements

• break and continue alter the flow of controla. break statement:

• The break statement when executed in while, for, do-while or switch structure causes immediate exit from that structure. The program continues with the first statement after the structure.

Example: What is the output of the following code?for (int x = 1; x<= 10; x++){

if ( x == 5 ) break; cout<<x<<" ";

}cout<<"\n broke out of the loop when x became "<<x<<endl;

181Prepared by Department of Computer

Science, Preparatory Year

Page 182: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Break and Continue Statements• break and continue alter the flow of control

b. continue statement:• The continue statement, when executed in a while, for, or do-

while structure skips the remaining statements in the body of that structure and proceeds with the next iteration of the loop.

Example: What is the output of the following code?

for (int x = 1; x<= 10; x++){

if ( x == 5 ) continue;

cout<<x<<" ";}cout<<"\n used continue to skip printing the value 5"<<endl;

182Prepared by Department of Computer

Science, Preparatory Year

Page 183: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Programming Using C++

Arrays and Strings

Prepared by Department of Computer Science, Preparatory Year 183

Page 184: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Introducing Arrays

• Arrays are data structures which hold multiple variables of the same data type.

• Consecutive group of memory locations having same name and type (int, char, float, double etc.)

• To refer to an element, Specify array name and position number (index) e.g. myList[5]

Prepared by Department of Computer Science, Preparatory Year 184

Page 185: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Introducing Arrays

Prepared by Department of Computer Science, Preparatory Year 185

Page 186: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Syntax

• Declaration: Datatype arrayname[ size] e.g. int A[20]int A[20] means A is an integers array with size 20.

• Each element in the array is accessed with a subscript i.e. A[0], A[1] ….. A[19]A[0], A[1] ….. A[19]

• Each memory element can hold an integer only.• First element at position 0 and the maximum position

at size 1‐• Memory requirements depend on the size of array.• Array declaration is static i.e. the size must be

specified at the time of declaration.

Prepared by Department of Computer Science, Preparatory Year 186

Page 187: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Initializing Arrays

• Declaring, creating, initializing in one step:– int a[5]={1,5,7,9,10]; a[0]=1, a[1]=5,…,a[4]=10

• If not enough initializers, rightmost elements 0, If too many syntax error :– int b[3] ={1}; b[0]=1,b[1]=0,b[2]=0.– int c[2] = {1,2,3,4} //Wrong

• To set every element to same value, e.g. int d[ 5] = { 0 };

• If array size omitted, initializers determine size i.e. int e[ ] = { 1, 2, 3, 4, 5 }; this implies size of a is 5

Prepared by Department of Computer Science, Preparatory Year 187

Page 188: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Initializing Arrays

• If A is an array and B is an array of same dimension (size) we can assign A = B i.e. the contents of B will be copied to array A.– Example:

int A[5]={11,33,55,66}, B[5]; B = A // means that all elements in A will be copied into

B .i.e. B[0]= 11,…,B[4] =66

Prepared by Department of Computer Science, Preparatory Year 188

Page 189: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

ExampleRead a set of integers and find the sum and average:void main( ) {

int a[20],i,sum=0,n; float average; cout << "How many integers to be taken: " ;cin >> n;for(i=0; i<n; i++) //Read and add to sum {

cout<<"Enter an integer:"; cin >> a[i]; sum = sum + a[i];

} average = sum / (float)n; cout << "sum= " << sum << endl << "average= " << average<<endl;

}

Prepared by Department of Computer Science, Preparatory Year 189

Page 190: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Multi Dimensional Arrays‐• Arrays can be more than one dimension i.e. two-dimensional, three-

dimensional etc.• Two-dimensional array: int A[10][12]:

– Here A is a two-dimensional array (or matrix) of size 10 x 12. The total memory locations are 120.

– Each location is referenced by two indices i.e. A[i][j]

– i varies from 0 to 9 and j varies from 0-11

• A[4][5] refers to cell located at 4th row and 5th column • Example of a 4 x 5 matrix

Prepared by Department of Computer Science, Preparatory Year 190

Page 191: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example• Read a array of size m x n and display the contentsvoid main() {

int A[50][50], i, j, m, n; cout << "Enter the row size:"; cin >> m; cout << "Enter the column size:"; cin >> n; cout << "Enter the array elements:“<<endl;for(i=0; i<m; i++) //read the elements row wise for(j=0; j<n; j++)

cin >> A[i][j]; cout << "The array elements are :" << endl; for( i=0; i<m; i++) {

for( j=0; j<n; j++) cout << A[i][j] << “\t\t”;

cout << endl; } }

Prepared by Department of Computer Science, Preparatory Year 191

Page 192: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Strings

• String is a character array always terminated with a null character ‘\0’

• char str1[10] str1 is a string where we can store maximum 9 characters.

• char str1[]={ 'h', 'e', 'l', 'l', 'o', '\0’ }; The length of the string is 7 ,and str[0] = ‘h’ and so on.

Prepared by Department of Computer Science, Preparatory Year 192

Page 193: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example • Read and Display a string#include <iostream> using namespace std;void main() {

char string[256]; // A nice long stringcout<<"Please enter a long string: "; cin>>string; // Input goes into stringcout<<"Your entered string is: "<< string <<endl;

}

Prepared by Department of Computer Science, Preparatory Year 193

Page 194: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

String Commands

• Need to include <string.h>• strlen (str): gives the length of the string str• strcpy(str1,str2) : copy the str2 to str1• strcmp(str1,str2) : Compares str1 with str2

and returns 0 if they are equal• strcat(str1,str2) : Concatenates str2 is

concatenated (appended) to str1

Prepared by Department of Computer Science, Preparatory Year 194

Page 195: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Examples

Prepared by Department of Computer Science, Preparatory Year 195

#include <iostream>#include <string.h>using namespace std; void main( ) { char string1[] = "Hello, world!"; char string2[20]; strcpy(string2, string1); cout<<string1<<'\t'<<string2; }

#include <iostream> #include <string.h> using namespace std; void main( ) { char string1[] = "Hello, world!"; char string2[20]= "How world"; if(strcmp(string1, string2) == 0) cout<<"strings are equal"; else cout<<"strings are unequal"; }

Page 196: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Examples

Prepared by Department of Computer Science, Preparatory Year 196

#include <iostream> #include <string.h> using namespace std; void main( ) { char string2[50] = "Hello"; char string1[50]="world !"; strcat(string2, string1); cout<<string1<<'\t'<<string2; }

#include <iostream> #include <string.h> using namespace std; void main( ) { char string1[] = "UQU Makkah"; cout<<strlen(string1); }

Page 197: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Programming Using C++

Functions

Prepared by Department of Computer Science, Preparatory Year 197

Page 198: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Introduction to functions

• A function is a group of statements that together perform a task. Every C++ program has at least one function which is main().

• Using functions we can construct our programs in a more modular way.

• There are two kinds of functions: those supplied to you and those which you are going to write.

Prepared by Department of Computer Science, Preparatory Year 198

Page 199: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Introduction to functions• Syntax:

type name ( parameter1, parameter2, ...) { statements }

where:• type is the data type specifier of the data returned by the function.• name is the identifier by which it will be possible to call the function.• parameters: Each parameter consists of a data type specifier followed by

an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.

• statements is the function's body. It is a block of statements surrounded by braces { }.

Prepared by Department of Computer Science, Preparatory Year 199

Page 200: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Function Declaration

• In order to create and use a function, you must tell the compiler to know. The syntax of declaring a function is:

ReturnType FunctionName();• An assignment, considered a function, is

made of three parts: its purpose, its needs, and the expectation. Based on this formula, the expectation you have from a function is the ReturnType factor

Prepared by Department of Computer Science, Preparatory Year 200

Page 201: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Function Declaration

• The simplest return type you can use is called, and represented as, void. Using this keyword, the simplest formula we can use is:

void FunctionName();

Prepared by Department of Computer Science, Preparatory Year 201

Page 202: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

• A function name follows the same rules we have applied to our variables.

• In addition, use a name that specifies what the function is expected to do. Usually, a verb is appropriate for a function that performs an action. Examples of names of functions are Add, Start, Assign, Play, etc.

Function Names

Prepared by Department of Computer Science, Preparatory Year 202

Page 203: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Function Definition

• In order to use a function in your program, you have to let the compiler know what the function does. To let the compiler know what the function is meant to do, you have to “define” it; which also means describing its behavior. The formula to define a function is:

void FunctionName() {Body}

Prepared by Department of Computer Science, Preparatory Year 203

Page 204: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Function Body• A function has a body. The body starts with

an opening curly bracket “{“ and ends with a closing curly bracket “}”.

• Example 1:void Message() {};• Example 2:void Message(){

cout << "This is C++ in its truest form.";} Prepared by Department of Computer

Science, Preparatory Year 204

Page 205: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Function Behaviour• A function can also implements a complete

behavior. • Imagine you want to calculate the area of a

square. You can define a particular function that would request the side of the square:

cout << “Enter the side of the square: “; cin >> Side; and let the function calculate the area using

the formula Area = Side * Side.

Prepared by Department of Computer Science, Preparatory Year 205

Page 206: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Function Examplevoid SquareArea() {

double Side; cout << "\nEnter the side of the square: "; cin >> Side; cout << "\nSquare characteristics:";cout << "\nSide = " << Side; cout << "\nArea = " << Side * Side;

}

Prepared by Department of Computer Science, Preparatory Year 206

Page 207: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Calling Function

• One of the main reasons of using various functions in your program is to isolate assignments; this allows you to divide the jobs among different entities so that if something is going wrong, you might easily know where the problem is.

• Functions trust each other so much that one function does not have to know HOW the other functions perform their assignments. One function simply needs to know what the other functions do, and what that other functions need.

Prepared by Department of Computer Science, Preparatory Year 207

Page 208: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Calling Functions• When calling one function from another function, provide neither the return value nor the body, simply type the name of the function and its list of arguments, if any. For example, to call a function named B() from the A() function, simply type it, like this:

Prepared by Department of Computer Science, Preparatory Year 208

Page 209: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Calling Functions

• C/C++ allows you to call a function before defining it.

• Unlike many languages, in C++, when calling a function, the compiler must be aware of the function.

• We have to declare a function before calling it. After calling the function, you can then define it as you see fit. Here is an example:

Prepared by Department of Computer Science, Preparatory Year 209

Page 210: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Calling Functions

Prepared by Department of Computer Science, Preparatory Year 210

Page 211: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Calling Functions• To use any of the functions that ship with the compiler, first include the library in which the function is defined, then call the necessary function. Here is an example that calls the getchar() function:

Prepared by Department of Computer Science, Preparatory Year 211

Page 212: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Void FunctionsImagine that we want to make a function just to show a message on the screen. We do not need it to return any value.

Prepared by Department of Computer Science, Preparatory Year 212

Page 213: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Void Functions• A function that does not return a value is

declared and defined as void. Here is an example:

Prepared by Department of Computer Science, Preparatory Year 213

Page 214: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Void Functions• Any function could be a void type as long as you are

not expecting it to return a specific value. A void function with a more specific assignment could be used to calculate and display the area of a square. Here is an example:

Prepared by Department of Computer Science, Preparatory Year 214

Page 215: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

The Type of Return Value• A return value, if not void, can be any of the

data types we have studied so far. This means that a function can return a char, an int, a float, a double…etc. Here are examples of declaring functions by defining their return values:

• double FunctionName(); • char FunctionName();

Prepared by Department of Computer Science, Preparatory Year 215

Page 216: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Function Example

Prepared by Department of Computer Science, Preparatory Year 216

Page 217: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Function Example• We can see how the main function begins by

declaring the variable z of type int. Right after that, we see a call to a function called addition.

• The parameters and arguments have a clear correspondence. Within the main function we called to addition passing two values: 5 and 3, that correspond to the int a and int b parameters declared for function addition.

Prepared by Department of Computer Science, Preparatory Year 217

Page 218: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Function Example• Function addition declares another local

variable (int r), and by means of the expression r=a+b, it assigns to r the result of a plus b.

• The following line of code:return (r);

• The following line of code in main is:cout << "The result is " << z;

Which will print the result on the screen.

Prepared by Department of Computer Science, Preparatory Year 218

Page 219: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Scope of Variables

• Variables that are declared inside a function or block are local variables.

• Local variables are not known to functions outside their own.

• Global variables are defined outside of all the functions, usually on top of the program. The global variables will hold their value throughout the lifetime of your program.

Prepared by Department of Computer Science, Preparatory Year 219

Page 220: Computer Programming (4800153-3) Department of Computer Science Preparatory Year 1433/1434 Prepared by Department of Computer Science, Preparatory Year.

Example of Global and Local Variables

Prepared by Department of Computer Science, Preparatory Year 220


Recommended