Sie sind auf Seite 1von 473

CHAPTER 8: PROGRAMMING

8.1 Introduction to Programming

sanggagakputih.blogspot.com

8.1 Introduction to Programming


8.1.1 Definition 8.1.2 Types of Programming Languages 8.1.3 Programming Language Paradigm 8.1.4 Translator

sanggagakputih.blogspot.com

8.1 Introduction to Programming

LEARNING OUTCOME:
At the end of this topic, students should be able to: 1. Define programming language. 2. Differentiate between Low-level and High-level Language. 3. State paradigms of programming language. 4. Identify the functions of translators.
sanggagakputih.blogspot.com 3

What is Programming ???

sanggagakputih.blogspot.com

Programming
A programming is a series of instructions that directs a computer to perform tasks. created by a programmer using a programming language. - instructions must be written in a way the computer can understand.

sanggagakputih.blogspot.com

Computer Program - Example

sanggagakputih.blogspot.com

What is a Programming Language ???

sanggagakputih.blogspot.com

Programming Language

Set of words, abbreviations, and symbols that enables a programmer to communicate instructions to a computer. - Discovering Computer 2011 -

sanggagakputih.blogspot.com

Programming Language

Languages that are used for


Writing games Writing application programs (like Excel)

sanggagakputih.blogspot.com

8.1.2 Types of Programming Language

Two Types

Low-level Language

High-level Language

sanggagakputih.blogspot.com
10

10

(1) Low-level Language

Programming language that is machine dependent that runs on only one particular type of computer.

These programs are not easily portable to other types of computer.

sanggagakputih.blogspot.com

11

Low-level Language Two Types

Machine Language

Assembly Language

sanggagakputih.blogspot.com
12

12

Low-level Language Machine


Language The FIRST generation of programming language The ONLY language that computer directly recognizes. Machine language instructions use a series of binary digits (1s and 0s) or combination of numbers and letters that represent binary digits.

sanggagakputih.blogspot.com 13

Low-level Language Machine


Language

Disadvantages: their instructions are extremely cryptic and difficult to learn programs are lengthy Machine-dependent not portable.
sanggagakputih.blogspot.com 14

Low-level Language Assembly


Language
The SECOND generation of programming language Using symbolic instruction codes (meaningful abbreviations) - A addition -C compare -L load - M multiply

sanggagakputih.blogspot.com

15

Low-level Language Assembly


Language

Disadvantages: Difficult to learn. (Programs must be convert to machine language before the computer can execute, or run the program.) Programmers must use assembler to convert assembly language to machine language.

sanggagakputih.blogspot.com

16

Low-level Language Assembly


Language

Disadvantages: programs are lengthy. Machine-dependent not portable.

sanggagakputih.blogspot.com

17

Low-level Language Assembly


Language

sanggagakputih.blogspot.com

18

(2) High-level Language


instructions are quite English-like

easier to learn than machine or assembly language a single instruction corresponds to many operations at the machine level
sanggagakputih.blogspot.com 19

High-level Language

have to be converted to machine-language before they can be executed Portable examples : FORTRAN, COBOL, BASIC, Pascal, Ada, C and C++

sanggagakputih.blogspot.com

20

8.1.3 Programming Language Paradigm


Computer languages are categorized according

to the approach they use to solve a problem.


A paradigm, is a way in which computer language looks at the problem to be solved. (style/architecture of programming language)

sanggagakputih.blogspot.com
21

21

FORTRAN COBOL BASIC C Pascal Ada

Smaltalk C++ Visual Basic Java C# F#

LISP Scheme

Prolog

sanggagakputih.blogspot.com
22

22

Object-Oriented - Java

sanggagakputih.blogspot.com

23

8.1.4 Translator Translator Program -- the program that translates the source program into the object program. Source Program -- program written in a highlevel programming language. Object Program -- the source program after it has been translated into machine language.

sanggagakputih.blogspot.com

24

8.1.4 Translator

Three Types
Assembler
converts programs written in assembly language to machine code

Interpreter
translates one high-level program instruction at a time into machine code
sanggagakputih.blogspot.com

Compiler
convert all of the source program into object program

25
25

8.1 Introduction to Programming

SUMMARY
Definition of programming language Differences between low-level and highlevel language Differences of the language paradigm in programming Functions of translator

sanggagakputih.blogspot.com
26

26

CHAPTER 8: PROGRAMMING
8.2 Approach in Problem Solving

sanggagakputih.blogspot.com

27

8.2 Approach in Problem Solving


8.2.1 Input Process Output (IPO) Analysis 8.2.2 Algorithm 8.2.3 Pseudocode 8.2.4 Flow Chart 8.2.5 Control Structure 8.2.5.1 Sequence 8.2.5.2 Selection 8.2.5.3 Looping
sanggagakputih.blogspot.com 28

8.2 Approach in Problem Solving

LEARNING OUTCOME:
At the end of this topic, students should be able to:

1. Identify input, process and output from a given problem. 2. Define algorithm. 3. Solve problem using pseudocode. 4. Solve problem using flow chart. 5. a) explain the purpose of each control structure. b) apply appropriate control structure in problem 29 solving. sanggagakputih.blogspot.com

Problem Solving Everyday in Life

sanggagakputih.blogspot.com

30

Problem Solving in Programming

Programming is a process of problem solving Problem solving techniques Analyze the problem Outline the problem requirements Specify what the solution should do Design steps, called an algorithm, to solve the problem (the general solution)
sanggagakputih.blogspot.com

31

8.2.1 Input Process Output (IPO) Analysis

The IPO is used to analyze problems and develop algorithms


Used to organize and summarize the results of a problem analysis It shows where in the solution the processing takes place
sanggagakputih.blogspot.com 32

8.2.1 Input Process Output (IPO) Analysis It can also be represent using IPO chart Input Processing
Processing items:

Output

Algorithm:

sanggagakputih.blogspot.com

33

8.2.1 Input Process Output (IPO) Analysis


Identify Input : Process : Output :

To do the IPO Analysis, start with: 1- Output (Display the results) 2- Input (Read the data) 3- Process (Perform the computation)
sanggagakputih.blogspot.com 34

8.2.1 Input Process Output (IPO) Analysis


Output should answer the following question:

What does the user want to see printed on the printer, displayed on the screen, or stored in a file?

sanggagakputih.blogspot.com

35

8.2.1 Input Process Output (IPO) Analysis


Input should answer the following question: What information will the computer need to know to print, display, or store the output items?

sanggagakputih.blogspot.com

36

8.2.1 Input Process Output (IPO) Analysis


Processing item:

An intermediate value that the algorithm uses when processing the input into the output

sanggagakputih.blogspot.com

37

Analyze the Problem


What is it you are trying to accomplish?
What outcome you are trying to arrive at? List the Inputs and Outputs

Often you work backwards from the Output List the Outputs, and then figure out what Inputs you need in order to arrive at the Output
sanggagakputih.blogspot.com 38

Analyze the Problem


Example 1 Problem statement: Calculate the area of a rectangle
width height

We can summarize the information contained in the problem statement as follows


sanggagakputih.blogspot.com 39

Analyze the Problem


Problem Analysis: Identify Input : Process : Output : To do the IPO Analysis, start with: 1 Output 2 Input sanggagakputih.blogspot.com 3 Process

40

Analyze the Problem


Problem Analysis:

Input:
Process: Output:

width, height
area = width x height area of rectangle
sanggagakputih.blogspot.com 41

IPO Chart
The Problem Analysis, can also be represent using IPO (Input, Processing, Output) Chart

Input
width, height

Processing
Processing items: area = width x height Algorithm:

Output
area of rectangle

sanggagakputih.blogspot.com

42

Analyze the Problem


Example 2 Problem statement:
Find the average of three numbers input by user.

We can summarize the information contained in the problem statement as follows...


sanggagakputih.blogspot.com 43

Analyze the Problem


Problem Analysis: Identify Input : Process : Output : To do the IPO Analysis, start with: 1 Output 2 Input sanggagakputih.blogspot.com 3 Process

44

Analyze the Problem


Problem Analysis:
Input: number1, number2, number3 Process: average = (number1 + number2 + number3) / 3 Output: average
sanggagakputih.blogspot.com 45

IPO Chart
Input Processing
Processing items:
number1, number2, number3

Output

average = (number1 + number2 + number3) / 3 Algorithm:

average

sanggagakputih.blogspot.com

46

Analyze the Problem


Example 3 Problem statement: Determine the total cost of durians, given the number of kilos of durians purchased and the cost of durians per kilo.

sanggagakputih.blogspot.com

47

Analyze the Problem


Problem Analysis: Identify Input : Process : Output : To do the IPO Analysis, start with: 1 Output 2 Input sanggagakputih.blogspot.com 3 Process

48

Analyze the Problem


Problem Analysis:
Input: Number of kilos of durians, Cost of durians per kilo Process: Total cost = Number of kilos of durians Cost of durians per kilo Output: Total cost of durians
sanggagakputih.blogspot.com 49

IPO Chart
Input Processing
Processing items:
Number of kilos of durians, Cost of durians per kilo

Output

Total cost = Number of kilos of durians x Cost of durians per kilo Algorithm:

Total cost of durians

sanggagakputih.blogspot.com

50

Analyze the Problem


Example 4 Problem statement: JKL Corporation gives a bonus to Irfan based on his sales. The bonus is 5 percent of the sales. Calculate Irfan's bonus.

sanggagakputih.blogspot.com

51

Analyze the Problem


Problem Analysis: Identify Input : Process : Output : To do the IPO Analysis, start with: 1 Output 2 Input sanggagakputih.blogspot.com 3 Process

52

Problem Analysis:
Input: Irfan's sales, Bonus rate of 5% Bonus = Sales x Bonus

Process: rate 5% Output:

Irfan's bonus

sanggagakputih.blogspot.com

53

IPO Chart
Input
Irfan's sales, Bonus rate of 5%

Processing
Processing items: Bonus = Sales x Bonus rate 5%

Output
Irfan's bonus

Algorithm:

sanggagakputih.blogspot.com

54

8.2.2 Algorithm
The algorithm is the abstract idea of solving a problem. An algorithm is a step-by-step instructions that will transform input into output.
It can be represent using pseudo code or flow chart.
sanggagakputih.blogspot.com

55

From Algorithms to Programs


Problem

Problem Analysis
Algorithm

sanggagakputih.blogspot.com C++ Program

56

Algorithm in everydays life


How to make a mug of hot coffee ??

sanggagakputih.blogspot.com

57

Algorithm in everydays life

How to make a mug of hot coffee: 1. Start 2. Boil water 3. Prepare a mug 4. Put a tea spoon of coffee & sugar 5. Pour hot water 6. Stir 7. End
sanggagakputih.blogspot.com 58

8.2.2 Algorithm
can be described using three control structures (Bohm and Jacopini-1966);
A Sequence is a series of statements that execute one after another A Selection (branch) statement is used to determine which of two different statements to execute depending on certain conditions

A Looping (repetition) sanggagakputih.blogspot.com 59 statement is used to repeat statements while certain conditions are met

Planning the Algorithm


1. Do Problem Analysis

Identify Input : Process : Output :


2. Transfer to pseudo code or flow chart 3. a. Must start with a start
sanggagakputih.blogspot.com 60

b. Must close with an end

TECHNIQUES TO REPRESENT THE ALGORITHM 1.Pseudo code 2.Flow Chart


Pseudo code Artificial, informal language used to develop algorithms Similar to everyday English Flow chart Graphical representation of an algorithm Special-purpose symbols connected by arrows (flow lines)
sanggagakputih.blogspot.com 61

TECHNIQUES TO REPRESENT THE ALGORITHM

xample of Pseudocode & Flow chart


Calculate the area of a circle

Pseudo code
Start: Input radius Calculate circle area circle area = 3.142 x radius x radius Print the circle area End:

Flow chart
start
radius circle area = 3.142 x radius x radius circle area end

sanggagakputih.blogspot.com

62

SUMMARY
1. Identify input, process and output from a given Problem. 2. Define algorithm.

sanggagakputih.blogspot.com

63

CHAPTER 8: PROGRAMMING
8.2 Approach in Problem Solving

sanggagakputih.blogspot.com

64

8.2 Approach in Problem Solving

LEARNING OUTCOME:
At the end of this topic, students should be able to: 1. Identify input, process and output from a given problem. 2. Define algorithm. 3. Solve problem using pseudo code. 4. Solve problem using flow chart.
sanggagakputih.blogspot.com 65

8.2.2 Algorithm
The algorithm is the abstract idea of solving a problem. An algorithm is a step-by-step instructions that will transform input into output.
It can be represent using pseudo code or flow chart.
sanggagakputih.blogspot.com

66

From Algorithms to Programs


Problem

1) Problem Analysis
2) Algorithm

sanggagakputih.blogspot.com C++ Program

67

Algorithm in everydays life


How to make a mug of hot coffee ??

sanggagakputih.blogspot.com

68

Algorithm in everydays life

How to make a mug of hot coffee: 1. Start 2. Boil water 3. Prepare a mug 4. Put a tea spoon of coffee & sugar 5. Pour hot water 6. Stir 7. End
sanggagakputih.blogspot.com 69

8.2.2 Algorithm
can be described using three control structures (Bohm and Jacopini-1966);
A Sequence is a series of statements that execute one after another A Selection (branch) statement is used to determine which of two different statements to execute depending on certain conditions

A Looping (repetition) sanggagakputih.blogspot.com 70 statement is used to repeat statements while certain conditions are met

Planning the Algorithm


1. Do Problem Analysis

Identify Input : Process : Output :


2. Transfer to pseudo code or flow chart 3. a. Must start with a start
sanggagakputih.blogspot.com 71

b. Must close with an end

TECHNIQUES TO REPRESENT THE ALGORITHM 1. Pseudo code 2. Flow Chart


Pseudo code Artificial, informal language used to develop algorithms Similar to everyday English Flow chart Graphical representation of an algorithm Special-purpose symbols connected by arrows (flow lines)
sanggagakputih.blogspot.com 72

TECHNIQUES TO REPRESENT THE ALGORITHM

xample of Pseudocode & Flow chart


Calculate the area of a circle

Pseudo code
Start: 1. Input radius 2. Calculate circle area: circle area = 3.142 x radius x radius 3. Print the circle area End:

Flow chart
start
radius circle area = 3.142 x radius x radius circle area end

sanggagakputih.blogspot.com

73

8.2.3 Pseudo Code

Artificial, informal language used to develop algorithms. Similar to everyday English.

sanggagakputih.blogspot.com

74

8.2.3 Pseudo Code

Pseudocode Format
1

start statement 1 statement 2 end


3
sanggagakputih.blogspot.com

2
The statement refers to any input, output & process involved
75

Example 1
Problem statement:

Calculate the area of a rectangle

width height
sanggagakputih.blogspot.com 76

Problem Analysis:

Input:
Process: Output:

width, height
area = width x height area of rectangle
sanggagakputih.blogspot.com 77

Pseudo Code Example 1

start 1. Input width, height 2. Compute area: area = width x height 3. Print area of rectangle end
sanggagakputih.blogspot.com 78

Example 2

Problem statement:

Find the average of three numbers input by user.

sanggagakputih.blogspot.com

79

Example 2 Problem Analysis:


Input: number1, number2, number3 Process: average = (number1 + number2 + number3) / 3 Output: average
sanggagakputih.blogspot.com 80

Pseudo Code Example 2

start 1. Input number1, number2, number3 2. Compute average: average = (number1 + number2 + number3) /3 3. Print average end
sanggagakputih.blogspot.com 81

Example 3
Problem statement:
Determine the total cost of durians, given the number of kilos of durians purchased and the cost of durians per kilo.

sanggagakputih.blogspot.com

82

Example 3 Problem Analysis:


Input: Number of kilos of durians, Cost of durians per kilo Process: Total cost = Number of kilos of durians Cost of durians per kilo Output: Total cost of durians
sanggagakputih.blogspot.com 83

Pseudo Code Example 3


start 1. Input number of kilos of durians, cost of durian per kilo. 2. Compute total cost of durian: total cost = number of kilos of durians x cost of durian per kilo 3. Print total cost of durian end
sanggagakputih.blogspot.com 84

Example 4
Problem statement:

JKL Corporation gives a bonus to Irfan based on his sales. The bonus is 5 percent of the sales. Calculate Irfan's bonus.

sanggagakputih.blogspot.com

85

Example 4 Problem Analysis:


Input: Irfan's sales, Bonus rate of 5% Bonus = Sales x Bonus

Process: rate 5% Output:

Irfan's bonus
sanggagakputih.blogspot.com 86

Pseudo Code Example 4

start 1. Input sales, bonus rate 2. Compute bonus: bonus = sales x bonus rate 3. Print bonus end

sanggagakputih.blogspot.com

87

8.2.4 Flow Chart

Graphical representation of an algorithm.


Special-purpose symbols connected by arrows (flow lines).
sanggagakputih.blogspot.com 88

Flow Chart Symbols


Graphic Symbol Name Terminal Symbol (ellipse) Meaning indicates the beginning and end points of an algorithm

Process Symbol (rectangle)

shows an instruction other than input, output or selection

Input-Output Symbol (parallelogram)

shows an input or output operation

sanggagakputih.blogspot.com

89

89

Flow Chart Symbols


Graphic Symbol Name Meaning

Disk Storage Input- indicates input from or output to disk Output Symbol storage (cylinder)

Printer Output Symbol


Selection Symbol (diamond)

shows hardcopy printer output

shows a selection process for two-way selection


90

sanggagakputih.blogspot.com

90

Flow Chart Symbols


Graphic Symbol Name Flow Lines (arrow) Off-Page Connector Meaning indicates the logical sequence execution steps in the algorithm of

provides continuation of a logical path on another page

On-Page Connector (circle)

provides continuation of a logical path at another point in the same page


91

sanggagakputih.blogspot.com

91

Flow Chart - Format


start

The statement refers to any input, output & process involved

Statement 1 Statement 2

end
sanggagakputih.blogspot.com 92
92

Example 1
Problem statement:

Calculate the area of a rectangle

width height
sanggagakputih.blogspot.com 93

Problem Analysis:

Input:
Process: Output:

width, height
area = width x height area of rectangle
sanggagakputih.blogspot.com 94

Flow chart - Example 1


start

width, height

area = width x height

area

sanggagakputih.blogspot.com

end

95

95

Example 2

Problem statement:

Find the average of three numbers input by user.

sanggagakputih.blogspot.com

96

Example 2 Problem Analysis:


Input: number1, number2, number3 Process: average = (number1 + number2 + number3) / 3 Output: average
sanggagakputih.blogspot.com 97

Flow chart - Example 2


start

number1, number2, number3

average = (number1 + number2 + number3) / 3

average

sanggagakputih.blogspot.com

end

98

98

Example 3
Problem statement:
Determine the total cost of durians, given the number of kilos of durians purchased and the cost of durians per kilo.

sanggagakputih.blogspot.com

99

Example 3 Problem Analysis:


Input: Number of kilos of durians, Cost of durians per kilo Process: Total cost = Number of kilos of durians Cost of durians per kilo Output: Total cost of durians
sanggagakputih.blogspot.com 100

Flow chart - Example 3


start

number of kilos of durians, cost of durian per kilo

total cost = number of kilos of durians x cost of durian per kilo

total cost

sanggagakputih.blogspot.com

end

101

101

Example 4
Problem statement:

JKL Corporation gives a bonus to Irfan based on his sales. The bonus is 5 percent of the sales. Calculate Irfan's bonus.

sanggagakputih.blogspot.com

102

Example 4 Problem Analysis:


Input: Sales, Bonus rate 5% Bonus = Sales x Bonus

Process: rate 5% Output:

Bonus
sanggagakputih.blogspot.com 103

Flow chart - Example 4


start

Sales, Bonus rate 5%

Bonus = Sales x Bonus rate 5%

Bonus

sanggagakputih.blogspot.com

end

104

104

EXERCISE

sanggagakputih.blogspot.com

105

Exercise 1
Problem statement: Pustaka Mukmin Bookstore offers 15% discount for each revision book. Calculate and display the price that customer should paid. Prepare IPO analysis, pseudo code & flow chart
sanggagakputih.blogspot.com 106

Problem Analysis:
Input: Price

Process:

Discount = Price x 15% New Price = Price - Discount New Price


sanggagakputih.blogspot.com 107

Output:

Problem Analysis:
Input: Price

Process:

New Price = Price x 85%

Output:

New Price

sanggagakputih.blogspot.com

108

Pseudo Code
start 1. Price 2. Compute Discount: Discount = Price x 15% 3. Compute New Price: New Price = Price Discount 4. Print New Price
end
sanggagakputih.blogspot.com 109

Flow chart
start

Price

Discount = Price x 15% New Price = Price - Discount

New Price

sanggagakputih.blogspot.com

end

110

110

SUMMARY
1. Identify input, process and output from a given problem. 2. Define algorithm. 3. Solve problem using pseudo code. 4. Solve problem using flow chart.

sanggagakputih.blogspot.com

111

CHAPTER 8: PROGRAMMING
8.2 Approach in Problem Solving
8.2.5 Control Structure

sanggagakputih.blogspot.com

112

8.2.5 Control Structure

LEARNING OUTCOME:
At the end of this topic, students should be able to: 1. Explain the purpose of each control structure. 2. Apply appropriate control structure in Problem solving.

sanggagakputih.blogspot.com

113

8.2.5 Control Structure Three (3) control structures


A

Sequence

is a series of statements that execute

one after another


A

Selection (branch)
sanggagakputih.blogspot.com 114

statement is used to determine which

of two different statements to execute depending on certain conditions

8.2.5.1 Sequence
Control Structures

SEQUENCE

SELECTION

LOOPING

sanggagakputih.blogspot.com

115

8.2.5.1 Sequence (Analogy) What do you do after wake up in the morning? Brush teeth Wash face Take a bath Comb hair Smile in front of mirror Having breakfast Go to class

sanggagakputih.blogspot.com 116

8.2.5.1 Sequence

The simplest programs consist just sequence of statements : no loops, no selections amongst alternative actions.

sanggagakputih.blogspot.com

117

8.2.5.1 Sequence Instruction in sequence programming are executed sequentially one by one. The sequence structure directs the computer to process the instructions, one after another, in the order listed in the program.
first instruction last instruction.
sanggagakputih.blogspot.com 118

Example 1

Problem statement:

Find the product of two numbers.

sanggagakputih.blogspot.com

119

Example 1 IPO Analysis:

Input: Process:

num1, num2 product = num1 x num2

Output:

product

sanggagakputih.blogspot.com

120

Example 1 Pseudo Code

start 1. Input num1, num2 2. Compute product: product = num1 x num2 3. Print product end

sanggagakputih.blogspot.com

121

Example 1 - Flow
start

chart

num1, num2

product = num1 x num2

product

sanggagakputih.blogspot.com

end

122

122

Example 2

Problem statement:
Find a volume for a cone. Formula :

sanggagakputih.blogspot.com

123

Example 2 IPO Analysis:


Input: radius, height Process: volume = (1/3) x 3.142 x radius x radius x height Output: volume
sanggagakputih.blogspot.com 124

Example 2 Pseudo Code

start 1. Input radius, height 2. Compute volume: volume = (1/3) x 3.142 x radius x radius x height 3. Print volume end
sanggagakputih.blogspot.com 125

Flow chart - Example 2


start

radius , height

volume = (1/3) x 3.142 x radius x radius x height

volume

sanggagakputih.blogspot.com

end

126

126

8.2.5.2 Selection
Control Structures

SEQUENCE

SELECTION

LOOPING

sanggagakputih.blogspot.com

127

8.2.5.2 Selection

Analogy
You need to choose to make Plain Coffee or Coffee Milk

sanggagakputih.blogspot.com

128

8.2.5.2 Selection
What is Selection Structure? The selection structure allows instructions to be executed non-sequentially.

It compares a condition / expression, and based on the result of the condition, it takes a certain course of action.
sanggagakputih.blogspot.com 129

8.2.5.2 Selection
Types of selection structures

if
One-way selection

if-else
Two-way selection

nested if-else
Multi-way selection

switch
Multi-way selection

sanggagakputih.blogspot.com

130

Selection - (1) if
The if construct has the general form
if (expression) statement

sanggagakputih.blogspot.com

131

Selection - (1) if
Expression is evaluated FIRST. If it evaluates to a non-zero value (TRUE), then statement is executed. If it evaluates to zero (FALSE), the statement is terminated. This structure has ONE entry point and ONE exit point.
sanggagakputih.blogspot.com 132

Selection - (1) if
Pseudo Code Format:

start 1. input 2. if (expression) Statement end


sanggagakputih.blogspot.com 133

Selection - (1) if
Flow chart Format:
False expression

True

statement
sanggagakputih.blogspot.com 134

Selection - (1) if [example]


Problem statement: Print message a is bigger than b if the value for a is bigger than b.

sanggagakputih.blogspot.com

135

Selection - (1) if
IPO Analysis:

Input:

a, b

Process: if ( a > b) print a is bigger than b Output: message a is bigger than b

sanggagakputih.blogspot.com

136

Selection - (1) if
Pseudo code:

start input a , b if (a > b) print a is bigger than b end


sanggagakputih.blogspot.com 137

Selection - (1) if
Flow chart
start

a, b

a>b

false

true
a is bigger than b
sanggagakputih.blogspot.com end 138

Selection - (1) if [example 2]


Problem statement: Print message PASS if marks for computer science test is greater than or equal to 60.

sanggagakputih.blogspot.com

139

Selection - (1) ifIPO Analysis:

Input:

marks

Process: if ( marks >= 60) print PASS Output: message PASS

sanggagakputih.blogspot.com

140

Selection - (1) if
Pseudo code:

start input marks if (marks >= 60) print PASS end


sanggagakputih.blogspot.com 141

Selection - (1) if
Flow chart
start

marks

marks >= 60

false

true
PASS
sanggagakputih.blogspot.com end 142

Selection - (2) if-else


The if-else construct has the general form
if (expression) statement 1 else statement 2
sanggagakputih.blogspot.com 143

Selection - (2) if-else


Expression is evaluated FIRST. If it evaluates to a non-zero value (TRUE), statement 1 is executed. If it evaluates to zero (FALSE), statement 2 is executed. Either statement 1 is executed or statement 2 BUT NOT BOTH.
sanggagakputih.blogspot.com 144

Selection - (2) if-else


Pseudo Code Format:
start 1. input 2. if (expression) Statement 1 else Statement 2 end
sanggagakputih.blogspot.com 145

Selection - (2) if-else


Flow chart Format:
False

expression

statement 2

True

statement 1
sanggagakputih.blogspot.com 146

Selection - (2) if-else


Example 1: Print Excellent! when user enter marks greater than or equal to 80, else print Sorry, try again.

sanggagakputih.blogspot.com

147

Selection - (2) if-else


IPO Analysis:

Input:

marks

Process: if (marks >= 80) print Excellent else print Sorry, try again Output: Excellent! or Sorry, try again
sanggagakputih.blogspot.com 148

Selection - (2) if-else


Pseudo code:

start input marks if (marks >= 80) print Excellent! else print Sorry, try again end
sanggagakputih.blogspot.com 149

Selection - (2) if-else


Flow chart
start marks

marks >= 80

false
Sorry, try again

true
Excellent!
sanggagakputih.blogspot.com end

150

Selection - (2) if-else


Example 2: A high school poetry competition is open only for students above 15 years old. Display Eligible if the students meet the requirement, else display Not eligible if otherwise.
sanggagakputih.blogspot.com 151

Selection - (2) if-else


IPO Analysis:

Input:

age

Process: if (age > 15) print Eligible else print Not eligible Output: Eligible or Not eligible
sanggagakputih.blogspot.com 152

Selection - (2) if-else


Pseudo code:

start input age if (age > 15) print Eligible else print Not eligible end
sanggagakputih.blogspot.com 153

Selection - (2) if-else


Flow chart
start age

age > 15

false
Not eligible

true
Eligible
sanggagakputih.blogspot.com end

154

Selection - (2) if-else


Example 3: If x is greater than y, display x is bigger than y else display x is smaller than y.

sanggagakputih.blogspot.com

155

Selection - (2) if-else


IPO Analysis:

Input:

x, y

Process: if ( x > y) print x is bigger than y else print x is smaller than y Output: x is bigger than y or sanggagakputih.blogspot.com x is smaller than y

156

Selection - (2) if-else


Pseudo code:

start input x, y if (x > y) print x is bigger than y else print x is smaller than y end
sanggagakputih.blogspot.com 157

Selection - (2) if-else


Flow chart
start

x,y

x>y

false
x is smaller than y

true
x is bigger than y
sanggagakputih.blogspot.com end

158

Selection - (3) nested if-else


The nested if-else structure can be nested to any depth.
if (expression 1) statement 1 else if (expression 2) statement 2 else if (expression n) statement n else last sanggagakputih.blogspot.com statement

159

Selection - (3) nested if-else


In this nested form, expression 1 is evaluated first. If it evaluates to nonzero (TRUE), statement 1 is executed and the entire statement is terminated. If not, control goes to the second if, where expression 2 is evaluated. If it evaluates to non-zero (TRUE), statement 2 is executed.
sanggagakputih.blogspot.com

160

Selection - (3) nested if-else


If not, expression n is evaluated. If it evaluates to non-zero (TRUE), statement n is executed. Otherwise, last statement will be executed. Only ONE of the statements will be executed.
sanggagakputih.blogspot.com 161

Selection - (3) nested if-else


Pseudo Code Format:
start 1. input 2. if (expression 1) statement 1 else if (expression 2) statement 2 else if (expression n) statement n else last statement sanggagakputih.blogspot.com end

162

Selection - (3) nested if-else


Flow chart Format: True
expression 1

statement 1

False
expression 2

True

statement 2

False

True
expression n

statement n

False last statement


sanggagakputih.blogspot.com 163

Selection - (3) nested if-else


Example 1:
if students grade is greater than or equal to 80 Print A else if students grade is greater than or equal to 60 Print B else if students grade is greater than or equal to 50 Print C else Print Failed
sanggagakputih.blogspot.com 164

Selection - (3) nested if-else


IPO Analysis:

Input: Process:

marks
if (marks >= 80) print A else if (marks >= 60) print B else if (marks >= 50) print C else print Failed

Output:

A orsanggagakputih.blogspot.com B or C or Failed

165

Selection - (3) nested if-else


Pseudo code:
start 1. input marks 2. if (marks >= 80) print A else if (marks >= 60) print B else if (marks >= 50) print C else print Failed end
sanggagakputih.blogspot.com 166

Selection - (3) nested if-else


Flow chart
start
marks

True
marks >=80

False
marks >=60

True
B C

False True
marks >=50

False
Failed

sanggagakputih.blogspot.com

167

end

Selection - (3) nested if-else


Example 2: if (x > 0) display "x is positive" else if (x < 0) display "x is negative" else display "x is 0"
sanggagakputih.blogspot.com 168

Selection - (3) nested if-else


IPO Analysis:

Input: Process:

x
if (x > 0) display "x is positive" else if (x < 0) display "x is negative" else display "x is 0"

Output:

x is positive or x is negative or x is 0sanggagakputih.blogspot.com

169

Selection - (3) nested if-else


Pseudo code:
start 1. input x 2. if (x > 0) display "x is positive" else if (x < 0) display "x is negative" else display "x is 0" end
sanggagakputih.blogspot.com 170

Selection - (3) nested if-else


Flow chart
start
x

True
X>0
x is positive

False
X<0

True
x is negative

False
x is 0

end
sanggagakputih.blogspot.com 171

Selection - (4) switch


The switch structure is a more elegant alternative to the complex nested if-else structure.

The switch structure lets user choose ONE of several alternatives.


Also known statement. as multiple-choice
172

sanggagakputih.blogspot.com

Selection - (4) switch


Switch structure has the general form:
switch (expression) { case expression 1: statement block break case expression 2: statement block break case expression n: statement block break default : statement block } sanggagakputih.blogspot.com

173

Selection - (4) switch


expression must evaluate to an integer or a character constant. Each alternative (except the default alternative) in the switch block is normally terminated with a break statement.

sanggagakputih.blogspot.com

174

Selection - (4) switch


The switch statement is executed as follows: The switch expression is evaluated FIRST. If it evaluates to expression 1, the statement block for that case is executed and break statement in the block terminates the entire switch statement.
sanggagakputih.blogspot.com 175

Selection - (4) switch


If the switch expression evaluates to expression 2, the statement block for that case is executed and break terminates the switch statement.

If the switch expression DOES NOT EVALUATE to any of the case expressions, the statement block for the default case is executed and then terminates the switch statement. sanggagakputih.blogspot.com

176

Selection - (4) switch


A break is NOT necessary for the default case since its execution will terminate the switch statement.

sanggagakputih.blogspot.com

177

Selection - (4) switch


Pseudo Code Format:
start 1. input 2. switch (expression) { case expression 1: statement block break case expression 2: statement block break case expression 'n': statement block break default : statement block } end
sanggagakputih.blogspot.com 178

Selection - (4) switch


Flow chart Format:

sanggagakputih.blogspot.com

179

Selection - (4) switch


Example 1:
x
1 2 Other value

Print
X is 1 X is 2 Value of x unknown

sanggagakputih.blogspot.com

180

Selection - (4) switch


IPO Analysis:

Input: Process:

x
switch (x)

{ case 1: Print "x is 1 break case 2: print "x is 2 break default: Print "value of x unknown

Output:

"x is 1" or "x is 2" or "value of x unknown sanggagakputih.blogspot.com

181

Selection - (4) switch


Pseudo code:
start 1. Input x 2. switch (x) { case 1: Print "x is 1 break case 2: Print "x is 2" break default: Print "value of x unknown } end sanggagakputih.blogspot.com

182

Flow chart

Selection - (4) switch

sanggagakputih.blogspot.com

183

EXERCISE

sanggagakputih.blogspot.com

184

Exercise 1: If student's grade is greater than or equal to 50, print Passed else print Failed.

Do IPO analysis, pseudo code and flow chart.


sanggagakputih.blogspot.com 185

SUMMARY
Types of selection structures

if
One-way selection

if-else
Two-way selection

nested if-else
Multi-way selection

switch
Multi-way selection

Use an appropriate selection control structure in problem solving sanggagakputih.blogspot.com 186

CHAPTER 8: PROGRAMMING
8.3 Introduction to C++

sanggagakputih.blogspot.com

187

8.3 Introduction to C++


8.3.1 Program Structure 8.3.2 Using Compiler
sanggagakputih.blogspot.com 188

LEARNING OUTCOME:
At the end of this topic, students should be able to: 8.3.1 Program Structure Identify components of C++. 8.3.2 Using Compiler Edit, compile, link and execute program.
sanggagakputih.blogspot.com 189

8.3.1 Program Structure


Components of C++: i. Comment ii. Preprocessor directive iii. Function iv. Body v. Return statement
sanggagakputih.blogspot.com 190

8.3.1 Program Structure


A computer program consists a list of instructions written in a computer language.
//This is my first C++ program //It prints a line of text #include <iostream> using namespace std;

i. comment ii.preprocessor directive iii. function iv. body

int main()
{ cout << "My first C++ program";

cin.get(); return 0;
}
sanggagakputih.blogspot.com

v. return statement

191

8.3.1 Program Structure


// rectangleAREA.cpp // Find Area of rectangle
#include <iostream> using namespace std; int main() { int width,height,area; cout << Enter value for width: ; cin >> width; cout << Enter value for height: ; cin >> height; area = width * height; cout << Area: << area; cin.get(); return 0; }
sanggagakputih.blogspot.com

i. comment

ii.preprocessor directive iii. function

iv. body

v. return statement

192

8.3.1 Program Structure


i. Comment
Style to insert a comment in C++.

i. Text begin with two double slash // - normally used for single line comment.

// This is my first C++ program // It prints a line of text

sanggagakputih.blogspot.com

193

i. Comment

sanggagakputih.blogspot.com

194

8.3.1 Program Structure


i. Comment
Style to insert a comment in C++.

begin with /* and ends with */ (possibly containing many lines)

ii.Text

/* This is my first C++ program It prints a line of text */


sanggagakputih.blogspot.com 195

i. Comment

sanggagakputih.blogspot.com

196

8.3.1 Program Structure


i. Comment The purpose to insert a comment: To document a program To improve program readability help other people read and understand a program. Remember comment DO NOT cause the computer to perform any action when the program is run.
sanggagakputih.blogspot.com 197

8.3.1 Program Structure


ii. Preprocessor directive Preprocessor directive is a general instruction to the C++ compiler. by

- Sharp sign ( #) :are processed preprocessor before program is compiled. - #include <iostream> tells the preprocessor to include in the program the contents of the input/output stream work properly. sanggagakputih.blogspot.com

198

8.3.1 Program Structure


ii. Preprocessor directive
- header file (with the file extension.h) is stored in the C++ library. - each header file contains a set of related functions.

sanggagakputih.blogspot.com

199

8.3.1 Program Structure


iii. Function

int main()

All C++ programs must have the main() function. The keyword void before main() indicates that main() will not return any value to the operating system. C++ programs normally begin executing at function main . sanggagakputih.blogspot.com 200

iii. Function

sanggagakputih.blogspot.com

201

8.3.1 Program Structure


iv. Body Function

- All the statements in a C++ function (main) must appear between a pair of curly braces { }. - The group of statements enclosed between the braces is called a function block.
sanggagakputih.blogspot.com 202

8.3.1 Program Structure


iv. Body Function

- The body of main may consist of:


a) variable declaration and reserved word e.g. : int width,height,area;
reserved word variables
203

sanggagakputih.blogspot.com

8.3.1 Program Structure


iv. Body Function - The body of main may consist of:
b) input / output console input console: use standard input stream object cin and input operator, >>, to allow user type in a value (or values). e.g. :

cin >> width;


sanggagakputih.blogspot.com 204

8.3.1 Program Structure


iv. Body Function - The body of main may consist of: b) input / output console output console: use standard output stream object - cout and the output operator, <<, to output the message. e.g. : cout << Area: << area;
sanggagakputih.blogspot.com 205

8.3.1 Program Structure


iv. Body Function - The body of main may consist of:

c) C++ statement - Every statement must end with semicolon (;) e.g. : i. cout << "My first C++ program; ii. area = width * height;
sanggagakputih.blogspot.com 206

8.3.1 Program Structure


v. return statement return 0; - is included at the end of main function. - value 0 indicates that the program has terminated successfully.

sanggagakputih.blogspot.com

207

8.3.2 Using Compiler


program.cpp (C++ source code) C++ compiler program.obj (object code)

Linker

C++ Library

program.exe (executable program)

Fig. 1: Building a C++ Program

sanggagakputih.blogspot.com

208

8.3.2 Using Compiler


Edit enter the program statement To write a C++ program, you need to enter the program statements by using:
Text editor (e.g. Notepad, Microsoft Word, etc.) Integrated Development Environment (IDE)(e.g. Dev C++, Borland C++, Visual C++, etc)

The complete source code.

program

statements

called

sanggagakputih.blogspot.com

209

8.3.2 Using Compiler


Compile translating C++ into machine code (also called object code)
Compiler determines the syntax error.

Link Run the linker combine the machine code with code from C++ library; after compiles is successful.

sanggagakputih.blogspot.com

210

8.3.2 Using Compiler


Execute Program an application can be run. Finally, the computer, under the control of its CPU, executes the program one instruction at a time. Compiler detects grammatical (syntax) error but NOT the program-logic error.

sanggagakputih.blogspot.com

211

8.3.2 Using Compiler


Tool Editor Step Edit Source code Compiler Compile Object code Linker Link Executable image Run Product

Result / Output
sanggagakputih.blogspot.com 212

SUMMARY
1. Identify components of C++.

2. Edit, compile, link and execute program.

sanggagakputih.blogspot.com

213

CHAPTER 8: PROGRAMMING
8.4 Data, Operator and Expression

sanggagakputih.blogspot.com

214

8.4.4

sanggagakputih.blogspot.com

215

8.4.1 Variables & Reserved Word

At the end of the lesson student should be able to:

Identify variables and reserved word.

sanggagakputih.blogspot.com

216

8.4.1 Variables & Reserved Word


C++ Character Set includes all the keyboard characters:

Uppercase letters of the English alphabet: AZ Lowercase letters of the English alphabet: az Numeric digits: 0 9 Special characters* (link to special characters) sanggagakputih.blogspot.com 217 Space (blank)

Special characters
Punctuation symbols: , . : ; ? ! Parentheses: ( ) Braces: { } Brackets: [ ] Quotation marks: Arithmetic symbols: + * / Comparison symbols: = > < Pound #, percent %, ampersand &, caret ^, tilde ~, vertical slash |, backslash \, underscore _.
sanggagakputih.blogspot.com 218

Identifiers/ User defined words


Words used to name constants, variables and functions. Identifiers are formed by combining letters, digits and underscore. Must be unique and have a meaningful names The first character MUST be a letter or an underscore. Reserved words CANNOT be used as identifiers. Identifiers are case-sensitive.
sanggagakputih.blogspot.com 219

Identifiers/ User defined words


Valid

vs.

Invalid
Student age Continue 17throw Principal+Interest 12 3X %change Data-1 Myfirst.c
220

gross_income city_tax student_age Item10 count Number_of_characters _abc ABC123Z7 X_1

sanggagakputih.blogspot.com

Variables
A variable is an identifier that is used to hold a value. Must be declared before they can be used. The general form of a declaration is dataType variable_list;
sanggagakputih.blogspot.com

221

Declaring variables:
#include <iostream> using namespace std; int main () { // declaring variables: char name; int age, home_address; float weight, height; return 0; }
sanggagakputih.blogspot.com 222

Keyword / Reserved Words

Keywords that identify language entities. Have special meanings to the compiler. Must appear in the correct location in a program, be typed correctly, and be used in the right context. Must be typed fully in lowercase.
sanggagakputih.blogspot.com 223

Keyword / Reserved Words

sanggagakputih.blogspot.com

224

8.4.2 Data Type

At the end of the lesson student should be able to: Identify various basic data types. Differentiate basic data type and their usage.
sanggagakputih.blogspot.com 225

Basic Data Type and Declaration

A set of data values and a set of operations on those values. Five classes:
character, integer, floating-point, float double floating-point, valueless, char int double void

sanggagakputih.blogspot.com

226

8.4.2 Data Type


Data Type: (i) char

Used to declare character variables (hold character value). For example:


char choice;
sanggagakputih.blogspot.com 227

8.4.2 Data Type


Data Type: (ii) int

Used to declare numeric program variables of integer type. (range: -32768 to 32767) Example:

int counter;
sanggagakputih.blogspot.com 228

8.4.2 Data Type


Data Type: (iii) float

Use to declare a floating-point variable. (approximately 6 digits of precision) For example: float gross_salary;
sanggagakputih.blogspot.com 229

8.4.2 Data Type


Data Type: (iv) double

Use to declare a floating-point variable (approximately 12 digits of precision) For example: double yearly_budget;
sanggagakputih.blogspot.com 230

8.4.2 Data Type


Data Type: (v) void
The type void either explicitly declares a function as returning no value or creates generic pointers. Example :

void main()
sanggagakputih.blogspot.com 231

All Data Types Defined by the ANSI/ISO C Standard


Type Typical Size in Bits Minimal Range

char
int

8
16 or 32

0 to 255
-32 768 to 32 767

float
double

32
64

6 digits of precision
12 digits of precision

ANSI American National Standards Institute for C programming language. ISO International Organization for Standardization
sanggagakputih.blogspot.com 232

Constants
Entities that appear in the program code as fixed values. const double pi = 3.14159; const char option = 'A'; Can be any of the basic data types. (char, int, float, double)

const int width = 8;

sanggagakputih.blogspot.com

233

Integer Constants

Positive or negative whole numbers with no fractional part. Consists of an optional plus (+) or a minus () sign and decimal digits.

sanggagakputih.blogspot.com

234

RULES for Decimal Integer Constants


Must begin with a non zero decimal digit Can contain decimal digit values of 0 - 9. If the sign is missing, the computer assumes positive. Commas are not allowed in integer constant.

sanggagakputih.blogspot.com

235

Decimal Integer Constants

Example :
Valid -15 0 +250 7550 const int num = -15;
sanggagakputih.blogspot.com

Invalid 0179 1F8 1,756

236

Character Constants

Character enclosed in single quotation marks. Examples: 'F' '1' '*' char genderFemale = 'F';
sanggagakputih.blogspot.com 237

String Constants

A sequence of any number of characters surrounded by double quotation marks. Useful in prompting users for input. Can contain any printable characters.

sanggagakputih.blogspot.com

238

String Constants - declaration

const char name[] = Hello World!;

sanggagakputih.blogspot.com

239

Floating-Point Constants

Positive or negative decimal numbers with an integer part, a decimal point, and a fractional part. Can be represented either in conventional or scientific notation.

sanggagakputih.blogspot.com

240

Scientific Notation

Consists of six (6) parts: A sign A decimal integer (optional) A decimal point A decimal fraction (optional) The letter e or E followed by a signed or unsigned integer exponent (optional) Type suffix f, F, l, or L (optional)
sanggagakputih.blogspot.com 241

Scientific Notation

Commas are not allowed. Three types: float double long double

sanggagakputih.blogspot.com

242

Scientific Notation

The following are examples of floatingpoint literals:


Floating Point
5.3876e4 53,876

Value
0.00000000004
100000 0.007321

4e-11
1e+5 7.321E-3

0.5e-6
0.45

0.0000005
0.45
sanggagakputih.blogspot.com 243

Escape Sequence / Backslash

The escape character and any character that follows. E.g:


Code \n \t \ \ \\ \? New line Horizontal tab Double quote Single quote Backslash
sanggagakputih.blogspot.com

Meaning

Question mark

244

Escape Sequence / Backslash : e.g

sanggagakputih.blogspot.com

245

Escape Sequence / Backslash :


output

sanggagakputih.blogspot.com

246

8.4.3 Operator

At the end of the lesson student should be able to:

clarify operations on variables operators that can be used in program. Identify precedence of operators
sanggagakputih.blogspot.com

& a

247

8.4.3 Operator

C++ uses a set of built-in operators. Operators act on operands. There are several operators:

sanggagakputih.blogspot.com

248

Arithmetic Operators
Operator Meaning
Subtraction, (also unary minus )
Addition

*
/

Multiplication
Division Modulus Division (produce the remainder of an integer division) Decrement
sanggagakputih.blogspot.com Increment 249

%
-++

8.4.3 Operator
Rules for Evaluation of Arithmetic Expressions:

Evaluate all parenthesized subexpressions, beginning with the innermost subexpressions in case they are nested. e.g: bill = 60 + ((hours 24) * 5);

sanggagakputih.blogspot.com

250

Increment and Decrement

C++ provides two special operators '++' and '-' for incrementing and decrementing the value of a variable by 1. The increment/decrement operator can be used with any type of variable BUT it cannot be used with any constant. Increment and decrement operators each have two forms, pre and post.
sanggagakputih.blogspot.com 251

Increment and Decrement


Increment Decrement

++x or x++ x=x+1

--x or x-x=x-1

x += 1 Pre: ++x Post: x++


sanggagakputih.blogspot.com

x -= 1 Pre: --x Post: x-252

Increment and Decrement

Expression
x---x

Meaning
decrease 1 after use in expression decrease 1 before use in expression

x++
++x

increase 1 after use in expression


increase 1 before use in expression

sanggagakputih.blogspot.com

253

Increment and Decrement ++x


x = 10; z = ++x; Here, z is equal to 11 x is equal to 11 x++ x = 10; z = x++; Here, z is equal to 10 x is equal to 11
sanggagakputih.blogspot.com 254

Increment and Decrement --x


x = 10; z = --x; Here, z is equal to 9 x is equal to 9 x-x = 10; z = x--; Here, z is equal to 10 x is equal to 9
sanggagakputih.blogspot.com 255

Increment and Decrement e.g: 1

int x,y; x = 5; y = x++ - 2;

int x,y; x = 5; y = ++x 2;

Answer: y=3 x=6

sanggagakputih.blogspot.com

Answer: y=4 x=6

256

Increment and Decrement e.g: 2

int y,z; y = 8; z = y-- + 3;

int y,z; y = 8; z = --y + 3;

Answer: y=7 z = 11

sanggagakputih.blogspot.com

Answer: y=7 z = 10

257

Increment and Decrement exercise 1

int x,y; x = 9; y = x++ + 8;

int x,y; x = 9; y = ++x + 8;

Answer: y=3 x=6

sanggagakputih.blogspot.com

Answer: y=4 x=6

258

Increment and Decrement exercise 1

int x,y; x = 9; y = x++ + 8;

int x,y; x = 9; y = ++x + 8;

Answer: y = 17 x = 10

sanggagakputih.blogspot.com

Answer: y = 18 x = 10

259

Increment and Decrement exercise 2

int y,z; y = 3; z = y-- - 1;

int y,z; y = 3; z = --y - 1;

Answer: y=7 z = 11

sanggagakputih.blogspot.com

Answer: y=7 z = 10

260

Increment and Decrement exercise 2

int y,z; y = 3; z = y-- - 1;

int y,z; y = 3; z = --y - 1;

Answer: y=2 z=2

sanggagakputih.blogspot.com

Answer: y=2 z=1

261

Increment and Decrement exercise 3

int a,b,n;

a = 5; b = 3;
n = ++a * ++b; Answer: n = a=
sanggagakputih.blogspot.com 262

Increment and Decrement exercise 3

int a,b,n;

a = 5; b = 3;
n = ++a * ++b; Answer: n = 24 a=6
sanggagakputih.blogspot.com 263

Increment and Decrement exercise 4

int a,b,n;

a = 7; b = 1;
n = a++ * --b; Answer: n = a=
sanggagakputih.blogspot.com 264

Increment and Decrement exercise 4

int a,b,n;

a = 7; b = 1;
n = a++ * --b; Answer: n = 0 a=8
sanggagakputih.blogspot.com 265

EXERCISE

Write the output for the program fragment given. 1) int z = 7;

cout << z << endl; cout << --z << endl; cout << z++ << endl;
sanggagakputih.blogspot.com 266

2) int p,q; p = 9; q = --p + 5; cout << --q << \t; cout << --p << endl; cout << p++ << endl;

sanggagakputih.blogspot.com

267

3) int p,q; p = 7; q = p++ - 3; cout << p << \t; cout << ++p << endl; cout << q++ << \t; cout << q << endl;

sanggagakputih.blogspot.com

268

4) int a = 3,b = 2, c;

c = 3 * ((5/a) + (4*(a-b)) % (a+b-2));

cout << ++c;

sanggagakputih.blogspot.com

269

ANSWER
1

7 6 6 12 7 7

8 9

4
5
4

sanggagakputih.blogspot.com

270

Relational Operator

The relational operators are used to test the relation between two values. All relational operators are binary operators and therefore require two operands. A relational expression returns zero (0) when the relation is FALSE and a non-zero (1) when it is TRUE.

sanggagakputih.blogspot.com

271

Relational Operator
Operator

Meaning
Greater than Greater than or equal Less than Less than or equal Equal
sanggagakputih.blogspot.com

> >= <

<=
== !=

Not equal

272

Relational Operator - examples

sanggagakputih.blogspot.com

273

Logical Operator

Logical refers to the ways these relationships can be connected.


Operator Meaning
AND
OR NOT
sanggagakputih.blogspot.com 274

&&
|| !

Logical Operator Truth Table


P 0 Q 0 P&&Q 0 P||Q 0 !P 1

0
1 1

1
0 1

0
0 1

1
1 1

1
0 0

sanggagakputih.blogspot.com

275

Logical & Relational Operator Example


i. ( 5 < 3 ) && (6 <= 6)
F T

Result: 0 (False)

ii.( 1 < 3 ) || (5 != 6)
T T

iii. ! (7 >=8)
F
276

Result: 1 (True) Result: 1 (True) sanggagakputih.blogspot.com

Assignment Operator

The assignment operator '=' is used for assigning a variable to a value. This operator takes the expression on its righthand-side and places it into the variable on its left-hand-side. For example:

m = 5; bill = 200;

sanggagakputih.blogspot.com

277

Assignment Operator

Other Examples:
a) sumProduct = x * y; b) bonus = 5 * salary; c) nett_income = gross deduction; d) modulus = a % b; e) BMI = width / (height * height);

sanggagakputih.blogspot.com

278

Precedence of Arithmetic and Relational Operators


Precedence Level
1 (highest) 2 3 4 5 6 ( ) Unary + ++ * + < == / <= !== > >= % unary --

Operator

Associativity
left to right right to left right to left left to right left to right left to right left to right

7 (lowest)

= += -= *= /= %=
sanggagakputih.blogspot.com

right to left
279

Presedence: Example 1

Assume a = 10, b = 3, c = 7 a+b


2

1)

>= 3 * c
3

13 >=

21
sanggagakputih.blogspot.com 280

Presedence: Example 2

Assume a = 10, b = 3, c = 7
a != 2 * c + b

3
10 !=

1
17

Output : 1 (true)
sanggagakputih.blogspot.com 281

Presedence: Example 3

int a; a=8+5*1%2*4
4 1 2 3

Output : 12

sanggagakputih.blogspot.com

282

8.4.4 Expression

At the end of the lesson student should be able to:

Write expression in correct syntax

sanggagakputih.blogspot.com

283

8.4.4 Expression

Expressions in C++ are formed by combining operators, variables and constants. C++ expressions can be simple or complex. Parentheses ( ) can be used to force the order of evaluation.
sanggagakputih.blogspot.com 284

8.4.4 Expression

Here are some examples of expressions:


nett_salary = (basic_pay + hours * rate) (socso + premium + loan);

(i)

(ii) (b * b 4 * a * c) > 0 (iii) (gender=='M' || gender=='F') && age >= 21

sanggagakputih.blogspot.com

285

8.4.4 Expression

sanggagakputih.blogspot.com

286

Mixed Mode Expression

Mixed mode expression happened when Constants and variables of different data types are combined together.

Type casting is used to force an expression to be of a specific data type.

sanggagakputih.blogspot.com

287

Type Casting

General forms:

(data_type) expression

OR data_type (expression)
sanggagakputih.blogspot.com 288

Type Casting - examples


float a, b; float addition, multiplication; float modulus;
addition = a + b; multiplication = a * b; modulus = (int) a % (int) b;

sanggagakputih.blogspot.com

289

Space and Parentheses

You can add tabs and spaces to expressions to make them easier to read. For example, the following two expressions are the same:

(i) x=10/y*(127/x); (ii) x = 10 / y * (127 / x);


sanggagakputih.blogspot.com 290

Space and Parentheses

Redundant or additional parentheses do not cause errors or slow down the execution of an expression.

You should use parentheses to clarify the exact order of evaluation, both for yourself and for others.

sanggagakputih.blogspot.com

291

Space and Parentheses

Which of the following two expressions is easier to read? x = y/3-34*temp+127;

x = (y/3) - (34*temp) + 127;

sanggagakputih.blogspot.com

292

SUMMARY
1. Identify variables and reserved word. 2. Identify various basic data types. 3. Differentiate basic data type and their usage. 4. Clarify operations on variables & operators that can be used in a program. 5. Identify precedence of operators. 6. Write expression in correct syntax.

sanggagakputih.blogspot.com

293

CHAPTER 8: PROGRAMMING
8.5 Use of Control Structure

sanggagakputih.blogspot.com

294

8.5 Use of Control Structure

At the end of the lesson student should be able to:

Write a program segment by using appropriate control structure.

sanggagakputih.blogspot.com

295

Control Structure

Control structure refers to the order of execution of instructions in a program. Types of control structure: Sequence Selection Looping
sanggagakputih.blogspot.com 296

From Algorithms to Programs


Problem

- Problem Analysis (IPO)


- Algorithm (Pseudo code + Flow chart)

sanggagakputih.blogspot.com C++ Program

297

(1) Sequence

Series of statements that execute one after another.

sanggagakputih.blogspot.com

298

(1) Sequence example 1


Calculate and display area of a circle.

IPO Analysis:

I - radius
P - area = 3.142 x radius x radius O - area

sanggagakputih.blogspot.com

299

(1) Sequence example 1


Pseudo code: Start Input radius Calculate area: area = 3.142 x radius x radius Display area End
sanggagakputih.blogspot.com 300

(1) Sequence example 1


#include <iostream> using namespace std; Pseudo code:
Start Input radius Calculate area: area = 3.142 x radius x radius Display area End

D I P O

int main() { float radius, area; cin >> radius;


area = 3.142 * radius * radius;

cout << area; cin.get(); sanggagakputih.blogspot.com return 0; NOT } USER FRIENDLY !!!
301

Why??
Because there is NO prompt message for user...

Assume that radius entered by user is 8.7

Sample of output:

sanggagakputih.blogspot.com

302

(1) Sequence example 1


#include <iostream> using namespace std; int main() D { I float radius, area;
P

"; O

cout << "Enter radius:


cin >> radius;
303

sanggagakputih.blogspot.com area = 3.142 * radius * radius;

(1) Sequence example 1


Sample of output:

sanggagakputih.blogspot.com

304

(1) Sequence example 2


Calculate and display total for three (3) quizzes below: Quiz1 78.5, Quiz2 67.5, Quiz3 90.2

IPO Analysis:
I - P - total = Quiz1 + Quiz2 + Quiz3 O - total
sanggagakputih.blogspot.com 305

(1) Sequence example 2


#include <iostream> using namespace std; int main() D { float Quiz1 = 78.5, Quiz2 = P 67.5; O float Quiz3 = 90.2, total;
total = Quiz1 + Quiz2 + sanggagakputih.blogspot.com Quiz3;

306

(1) Sequence example 2


Sample of output:

sanggagakputih.blogspot.com

307

(1) Sequence example 3


Calculate and display price of laptop after 15% discount.
IPO Analysis:

I - ori price
P - new price = ori price x 0.85

O - new price
sanggagakputih.blogspot.com 308

(1) Sequence example 3


#include <iostream> using namespace std; int main() { float ori_price, new_price;
cout << Insert original price: RM ; cin >> ori_price; 0.85; new_price = ori_price *
sanggagakputih.blogspot.com 309

(1) Sequence example 3


Sample of output:

sanggagakputih.blogspot.com

310

The following C++ code contains errors. Correct the error and rewrite the code. #include (iostream.h) #include (stdlib.h) int main() { char name[25];

cout >> 'Enter your name: '; cin << name


sanggagakputih.blogspot.com 311

cout << "Your name is "

Errors: #include (iostream.h) #include (stdlib.h) int main() { char name[25];

cout >> 'Enter your name: '; cin << name


sanggagakputih.blogspot.com 312

cout << "Your name is "

Answer: #include <iostream.h> #include <stdlib.h> int main() { char name[25];

cout << Enter your name: ; cin >> name;


sanggagakputih.blogspot.com 313

cout << "Your name is "

Sample of output:

sanggagakputih.blogspot.com

314

The program may contains error(s). Correct the error and rewrite the program. #include <iostream.h> #include <stdlib.h> void main() { double dist_km double dist_mile; cout << "\n Enter the distance in \"KM\:";
sanggagakputih.blogspot.com 315

CIN >> dist_km;

Errors: #include <iostream.h> #include <stdlib.h> void main() { double dist_km double dist_mile; cout << \n Enter the distance sanggagakputih.blogspot.com in \KM\:; CIN >> dist_km;

316

Answer: #include <iostream.h> #include <stdlib.h> void main() { double dist_km; double dist_mile; cout << \n Enter the distance sanggagakputih.blogspot.com in \KM\:; cin >> dist_km;

317

Study the C++ program below. Using problem analysis, determine input, output and process involve in this program.

#include <iostream.h> #include <stdlib.h> int main() { int feet, yards;

cout << Enter value (yards)


cin >> sanggagakputih.blogspot.com yards;
318

feet = 3 * yards;

Answer:

IPO Analysis: I - yards

P - feet = 3 * yards
O - feet
sanggagakputih.blogspot.com 319

Exercise:
(1) Write a complete C++ program that will calculate salary earned when user enter number of days worked and rate per day. Your output should display number of days worked, rate per day and amount earned. (2) Write a complete C++ program that will calculate amount paid for an item when user enter quantity and price of the item. The output must display the quantity, price of the item and amount paid. (3) Write a C++ program that will calculate and output the average of two floating-point numbers sanggagakputih.blogspot.com 320 entered from the keyboard.

Answer:
(1) Write a complete C++ program that will calculate salary earned when user enter number of days worked and rate per day. Your output should display number of days worked, rate per day and amount earned.

IPO Analysis:
I - days worked, rate P - salary = days worked x rate

O - days worked, rate, salary sanggagakputih.blogspot.com

321

Program:

sanggagakputih.blogspot.com

322

Sample of output:

sanggagakputih.blogspot.com

323

Answer:
(2) Write a complete C++ program that will calculate amount paid for an item when user enter quantity and price of the item. The output must display the quantity, price of the item and amount paid

IPO Analysis:
I - quantity, price P - amount paid = quantity x price

O - quantity, price, amount paid sanggagakputih.blogspot.com

324

Program:

sanggagakputih.blogspot.com

325

Sample of output:

sanggagakputih.blogspot.com

326

Answer:
(3) Write a C++ program that will calculate and output the average of two floating-point numbers entered from the keyboard

IPO Analysis:
I - num1, num2 P - average = (num1 + num2) / 2

O - average

sanggagakputih.blogspot.com

327

Program:

sanggagakputih.blogspot.com

328

Sample of output:

sanggagakputih.blogspot.com

329

(2) Selection
The selection structure allows instructions to be executed non-sequentially.

It compares a condition / expression, and based on the result of the condition, it takes a certain course of action.

sanggagakputih.blogspot.com

330

(2) Selection
Types of selection structures

if
One-way selection

if-else
Two-way selection

nested if-else
Multi-way selection

switch
Multi-way selection

sanggagakputih.blogspot.com

331

(2) Selection [if] example 1


Print Passed! when user enter marks greater than or equal to 60.
IPO Analysis: Input: marks Process: if (marks >= 60) print Passed!

Output:

message Passed!
sanggagakputih.blogspot.com 332

(2) Selection [if] example 1


#include <iostream> using namespace std; int main() { float marks; cout << "Enter marks: "; cin >> marks; if (marks >= 60) sanggagakputih.blogspot.com cout << "\nPassed!";
333

(2) Selection [if] example 1


Sample of output:

sanggagakputih.blogspot.com

334

(2) Selection [if] example 2


Assign car allowance = 200 and housing allowance = 800 if job code for a worker is equal to '1'.
IPO Analysis:
Input: job code Process: if (job code == '1') car allowance = 200 housing allowance = 800 Output: sanggagakputih.blogspot.com 335

(2) Selection [if] example 2


#include <iostream> using namespace std; int main() { char job_code; float car_allowance, housing_allowance; cout << "Enter your job code: "; sanggagakputih.blogspot.com cin >> job_code;

336

(2) Selection [if] example 2


Sample of output:

sanggagakputih.blogspot.com

337

(2) Selection [if-else] example 1


Print Excellent! when user enter marks greater than or equal to 80, else print Sorry, try again.
IPO Analysis:
Input: marks Process: if (marks >= 80) print Excellent else print Sorry, try again

Output:

Excellent! or Sorry, try again sanggagakputih.blogspot.com

338

(2) Selection [if-else] example 1


#include <iostream> using namespace std; int main() { float marks; cout << "Enter marks: "; cin >> marks; if (marks >= 80) sanggagakputih.blogspot.com cout << "\nExcellent"; else
339

(2) Selection [if-else] example 1


Sample of output:

sanggagakputih.blogspot.com

340

(2) Selection [if-else] example 2


Calculate price of car rental. Customer will charged for RM 60 if total hours less or equal to 24. Otherwise, RM 5 will be charged for next every hour. Display the price of car rental.
IPO Analysis:

Input: hours Process: if (hours <= 24) amount paid = 60 print amount paid else amount paid = 60 + ((hours 24) x 5 ) print amount paid
Output: amountsanggagakputih.blogspot.com paid
341

(2) Selection [if-else] example 2


#include <iostream> using namespace std; int main() { int hours; float amount_paid;

cout << "Enter total hours: "; cin >> hours;


sanggagakputih.blogspot.com 342

if (hours <= 24)

(2) Selection [if-else] example 2

sanggagakputih.blogspot.com

343

(2) Selection [if-else] example 2


Sample of output:

sanggagakputih.blogspot.com

344

(2) Selection [nested if-else] example


1 This program prompts the user to enter a number. If that number is greater than zero, it tells the user that a positive number was entered. If the number is less than zero, it tells the user that a negative number was entered. If both are not true, it tells the user that the number is equal to zero.

sanggagakputih.blogspot.com

345

(2) Selection [nested if-else] example


1
IPO Analysis: Input: num Process: if (num > 0) print Positive Number else if (num < 0) print Negative Number else print Number is equal to zero Output: message Positive Number OR Negative Number OR Number is equal to zero
sanggagakputih.blogspot.com 346

(2) Selection [nested if-else] example


1
#include <iostream> using namespace std; int main() { int num; cout << "Enter any number: "; cin >> num; if (num > 0)
sanggagakputih.blogspot.com 347

(2) Selection [nested if-else] example


1

sanggagakputih.blogspot.com

348

(2) Selection [nested if-else] example


1
Samples of output:

sanggagakputih.blogspot.com

349

(2) Selection [nested if-else] example


2 Computes and prints the product or total of three numbers based on the user request. If user request is 1, the program will count the product of three numbers. If it is 2, the program will count the total of three numbers. If the number is not 1 or 2, display this message; You make a wrong choice.

sanggagakputih.blogspot.com

350

(2) Selection [nested if-else] example


2
IPO Analysis: Input: user request, num1, num2, num3 Process: if (user request == 1) product = num1 x num2 x num3 print product else if (user request == 2) total = num1 + num2 + num3 print total else print You make a wrong choice!

Output:

product OR total OR message You make a wrong choice! sanggagakputih.blogspot.com

351

(2) Selection [nested if-else] example


2

sanggagakputih.blogspot.com

352

(2) Selection [nested if-else] example


2
Samples of output:

sanggagakputih.blogspot.com

353

(2) Selection [nested if-else] example


2

sanggagakputih.blogspot.com

354

(2) Selection [nested if-else] example


2
Samples of output:

sanggagakputih.blogspot.com

355

(2) Selection [switch] example 1


Computes and prints the product or total of three numbers based on the user request. If user request is 1, the program will count the product of three numbers. If it is 2, the program will count the total of three numbers. If the number is not 1 or 2, display this message; You make a wrong choice.

sanggagakputih.blogspot.com

356

(2) Selection [switch] example 1


IPO Analysis:

Input: user request, num1, num2, num3 Process: switch (user request) { case 1 : product = num1 x num2 x num3 print product break case 2 : total = num1 + num2 + num3 print total break default: print You make a wrong choice! } Output: product OR total sanggagakputih.blogspot.com OR message You make a wrong choice!

357

(2) Selection [switch] example 1

sanggagakputih.blogspot.com

358

Switch
switch (user_request) { case 1 : product = num1 * num2 * num3; cout << "\nProduct of three number is: " << product; break; case 2 : total = num1 + num2 + num3; cout << "\nTotal of three number is: " << total; Break;

Nested if-else equivalent


`if (user_request == 1) { product = num1 * num2 * num3; cout << "\nProduct of three number is: " << product; }

else if (user_request == 2) { total = num1 + num2 + num3; cout << "\nTotal of three number is: " << total; }

default: cout << "\nYou make a wrong choice!"; }

else sanggagakputih.blogspot.com cout << "\nYou make a wrong choice!";

359

(2) Selection [switch] example 2


This program needs user to key in a number to make a choice for their favorite's holiday destination in Malaysia. If the choice is equal to 1, it will display Pulau Langkawi. If the choice is equal to 2, it will display Cameron Highland. If the choice is equal to 3, it will display Genting Highland. If the choice is equal to 4, it will display Bukit Merah. Other than that, display Your choice is not in the list.
sanggagakputih.blogspot.com 360

(2) Selection [switch] example 2


IPO Analysis:
Input: user choice Process: switch (user choice) { case 1 : print Pulau Langkawi break case 2 : print Cameron Highland break case 3 : print Genting Highland break case 4 : print Bukit Merah break default: print Your choice is not in the list } Output: Pulau Langkawi or Cameron Highland or sanggagakputih.blogspot.com Genting Highland or Bukit Merah or You make a wrong choice!

361

(2) Selection [switch] example 2

sanggagakputih.blogspot.com

362

(2) Selection [switch] example 2


Samples of output:

sanggagakputih.blogspot.com

363

Switch
switch (user_choice) { case 1 : cout << "\nPulau Langkawi "; break; case 2 : cout << "\nCameron Highland "; break;

Nested if-else equivalent


`if (user_choice == 1) cout << "\nPulau Langkawi ";

else if (user_choice == 2) cout << "\nCameron Highland "; else if (user_choice == 3) cout << "\nGenting Highland "; else if (user_choice == 4) cout << "\nBukit Merah ";

case 3 : cout << "\nGenting Highland "; break;


case 4 : cout << "\nBukit Merah "; break;

default: cout << "\nYour choice is not in the list"; else sanggagakputih.blogspot.com 364 } cout << "\nYour choice is not in the list";

What is the output for this program if color value is 'R' ?

sanggagakputih.blogspot.com

365

Output:

sanggagakputih.blogspot.com

366

What is the output for this program code?

sanggagakputih.blogspot.com

367

Output:

sanggagakputih.blogspot.com

368

Study the following fragment code.

int n;
cout << "Enter integer: " << endl; cin >> n;

if (n < 5) cout << "\nan integer entered less than 5 "; else if (n > 5) (i) What will be the output if user enters the integer value is 0 cout << "\nan integer entered (ii) What values for n will cause the output an integer entered not greater than 5 "; interesting ? sanggagakputih.blogspot.com 369
else

(i) What will be the output if user enters the integer value is 0 Answer : an integer entered less than
5 (ii) What values for n will cause the output an integer entered not interesting ? Answer : n = 5
sanggagakputih.blogspot.com 370

(3) Looping
The looping (or repetition) structure allows a sequence of instructions to be executed repeatedly until a certain condition is reached. The looping structure has three forms: while do-while for
sanggagakputih.blogspot.com 371

Looping (1) while example 1


Display Hello for five (5) times

IPO Analysis: I - none P - none

O - Hello for five (5) times


sanggagakputih.blogspot.com 372

Looping (1) while example 1


start 1. initialize counter i=1 2. while (i <= 5) { print Hello 3. counter increment i=i+1 } 4. repeat until i > 5 end
sanggagakputih.blogspot.com

start
i=1

F
end i <= 5

T
Hello

i=i+1
373

Looping (1) while example 1

sanggagakputih.blogspot.com

374

Looping (1) while example 1


Output:

sanggagakputih.blogspot.com

375

Looping (1) while example 2


Find the average of three numbers for three (3) times
IPO Analysis: I - num1, num2, num3

P - average = (num1 + num2 + num3) / 3


O - average (3 times)
sanggagakputih.blogspot.com 376

Looping (1) while example 2

sanggagakputih.blogspot.com

377

Looping (1) while example 2


Sample of output:

sanggagakputih.blogspot.com

378

Looping (1) while example 3


Calculate area of a circle two for (2) times

IPO Analysis: I - radius

P - area = 3.142 x radius x radius


O - area (2 times)
sanggagakputih.blogspot.com 379

Looping (1) while example 3

sanggagakputih.blogspot.com

380

Looping (1) while example 3


Sample of output:

sanggagakputih.blogspot.com

381

Looping (1) while trace output 1

sanggagakputih.blogspot.com

382

Looping (1) while answer

sanggagakputih.blogspot.com

383

Looping (1) while trace output 2

sanggagakputih.blogspot.com

384

Looping (1) while answer

sanggagakputih.blogspot.com

385

Looping (2) do-while example 1


Display C++ for seven (7) times

IPO Analysis: I - none P - none

O - C++ (7 times)
sanggagakputih.blogspot.com 386

Looping (2) do-while example 1


start 1. initialize counter i=1 2. do { print C++ 3. counter increment i=i+1 } 4. while ( i <=7) repeat while i <= 7 end
start
i=1

C++

i=i+1
T
i <= 7

F
sanggagakputih.blogspot.com 387

end

Looping (2) do-while example 1

sanggagakputih.blogspot.com

388

Looping (2) do-while example 1


Output:

sanggagakputih.blogspot.com

389

Looping (2) do-while example 2


Find the average of three numbers for three (3) times
IPO Analysis: I - num1, num2, num3

P - average = (num1 + num2 + num3) / 3


O - average (3 times)
sanggagakputih.blogspot.com 390

Looping (2) do-while example 2

sanggagakputih.blogspot.com

391

Looping (2) do-while example 3


Calculate area of a circle two for (2) times

IPO Analysis: I - radius

P - area = 3.142 x radius x radius


O - area (2 times)
sanggagakputih.blogspot.com 392

Looping (2) do-while example 3

sanggagakputih.blogspot.com

393

Looping (3) for example 1


Display I Love KMM for ten (10) times

IPO Analysis: I - none P - none

O - I Love KMM (10 times)


sanggagakputih.blogspot.com 394

Looping (3) for example 1

sanggagakputih.blogspot.com

395

Looping (3) for example 1


Output:

sanggagakputih.blogspot.com

396

Looping (3) for example 2


Find the average of three numbers for three (3) times
IPO Analysis: I - num1, num2, num3

P - average = (num1 + num2 + num3) / 3


O - average (3 times)
sanggagakputih.blogspot.com 397

Looping (3) for example 2

sanggagakputih.blogspot.com

398

Looping (3) for example 3


Calculate area of a circle two for (2) times

IPO Analysis: I - radius

P - area = 3.142 x radius x radius


O - area (2 times)
sanggagakputih.blogspot.com 399

Looping (3) for example 3

sanggagakputih.blogspot.com

400

EXERCISE (1)
Change the C++ segment code below into for & do-while statement.
int i = 7; while ( i <= 77) { cout << i << endl; i = i + 7; }
sanggagakputih.blogspot.com 401

EXERCISE (2)
Change the C++ segment code below into while & do-while statement.
int j; for (j=20; j >= 2; j-=2) { cout << j << endl; }
sanggagakputih.blogspot.com 402

EXERCISE (3)

The following C++ codes containe errors. Correct the errors and rewrite the code.

#include <iostream.h> #include <stdlib.h>

int main[]
{ int Num, Power, bil; cout << Please key in any number: ; cin >> Num; for (bil == 1, bil <= 12; bil++;) { Power = bil x num; cout << bil << x << num << = << Power << endl; } cin.get();
sanggagakputih.blogspot.com 403

EXERCISE (4)
a) Write a program segment that will display value 1 to 100 in increments of 1. (while, do-while, for)

b) Write a program segment that will display value 100 to 1 in decrements of 1. (while, do-while, for)

sanggagakputih.blogspot.com

404

EXERCISE (1) - Answer


for statement.
int i; for (i=7; i <= 77; i=i+7) { cout << i << endl;

sanggagakputih.blogspot.com

405

EXERCISE (1) - Answer


do-while statement.
int i = 7; do { cout << i << endl; i = i + 7;

} while(i <= 77);

sanggagakputih.blogspot.com

406

EXERCISE (2) - Answer


while statement.

int j = 20; while (j >= 2) { cout << j << endl; j-=2; }


sanggagakputih.blogspot.com 407

EXERCISE (2) - Answer


do-while statement.

int j = 20; do { cout << j << endl; j-=2; } while (j >= 2);
sanggagakputih.blogspot.com 408

EXERCISE (3) - Answer


#include <iostream.h> #include <stdlib.h> int main( ) { int Num, Power, bil; cout << Please key in any number: ; cin >> Num;

for (bil = 1; bil <= 12; bil++)


{ Power = bil * Num; cout << bil << x << Num << = << Power << endl; } cin.get(); return 0; }
sanggagakputih.blogspot.com 409

EXERCISE (4) - Answer


a) Write a program segment that will display value 1 to 100 in increments of 1. (while, do-while, for)
int j = 1;
while (j <= 100) { cout << j << endl; j++; }
sanggagakputih.blogspot.com 410

EXERCISE (4) - Answer


b) Write a program segment that will display value 100 to 1 in decrements of 1. (while, do-while, for)
int j = 100;
do { cout << j << endl; j--; } while (j >= 1);
sanggagakputih.blogspot.com 411

Applying accumulating in looping


Accumulating or summing is a task that most often perform in C++. Accumulating means summing a group of numbers: 1. where a variable is added to another variable, 2. which holds the value of the sum or total.

sanggagakputih.blogspot.com

412

Expression for accumulating: (e.g:)

sum = sum + num

total = total + marks

sanggagakputih.blogspot.com

413

Example 1:
Calculate and display sum of odd numbers from 1 to 10

IPO Analysis: I - none

P - sum = sum + counter


O - sum
sanggagakputih.blogspot.com 414

Example 1: while
int counter = 1; int sum = 0; while ( counter <= 10 ) { sum = sum + counter; counter = counter + 2; } cout << Sum of ODD numbers is: << sum;

sanggagakputih.blogspot.com

415

Example 1: while

sanggagakputih.blogspot.com

416

Example 1: do-while
int counter = 1; int sum = 0; do { sum = sum + counter; counter = counter + 2; } while ( counter <= 10 ); cout << Sum of ODD numbers is: << sum;
sanggagakputih.blogspot.com 417

Example 1: do-while

sanggagakputih.blogspot.com

418

Example 1: for
int counter; int sum = 0; for (counter = 1; counter <= 10; counter = counter + 2) { sum = sum + counter; } cout << Sum of ODD numbers is: << sum;

sanggagakputih.blogspot.com

419

Example 1: for

sanggagakputih.blogspot.com

420

Example 1:
Output:

sanggagakputih.blogspot.com

421

Example 2:
Calculate and display sum of EVEN numbers from 2 to 20

IPO Analysis: I - none

P - sum = sum + counter


O - sum
sanggagakputih.blogspot.com 422

Example 2: while
int counter = 2; int sum = 0; while ( counter <= 20 ) { sum = sum + counter; counter = counter + 2; } cout << Sum of EVEN numbers is: << sum;

sanggagakputih.blogspot.com

423

Example 2: while

sanggagakputih.blogspot.com

424

Example 2: do-while
int counter = 2; int sum = 0; do { sum = sum + counter; counter = counter + 2; } while ( counter <= 20 ); cout << Sum of EVEN numbers is: << sum;
sanggagakputih.blogspot.com 425

Example 2: do-while

sanggagakputih.blogspot.com

426

Example 2: for
int counter; int sum = 0; for (counter = 2; counter <= 20; counter = counter + 2) { sum = sum + counter; } cout << Sum of EVEN numbers is: << sum;

sanggagakputih.blogspot.com

427

Example 2: for

sanggagakputih.blogspot.com

428

Example 2:
Output:

sanggagakputih.blogspot.com

429

Example 3:
Calculate and display average of three (3) quizzes.
IPO Analysis: I - mark P - total = total + mark average = total / 3 O - average
sanggagakputih.blogspot.com 430

Example 3: while
int counter = 1; float total = 0, mark, average;
while ( counter <= 3 ) { cout << Enter mark: ; cin >> mark; total = total + mark; counter++; } average = total / 3; cout << Average for 3 quizzes: << average;
sanggagakputih.blogspot.com 431

Example 3: while

sanggagakputih.blogspot.com

432

Example 3: do-while
int counter = 1; float total = 0, mark, average;
do { cout << Enter mark: ; cin >> mark; total = total + mark; counter++; } while ( counter <= 3 ); average = total / 3; cout << Average for 3 quizzes: << average;
sanggagakputih.blogspot.com 433

Example 3: do-while

sanggagakputih.blogspot.com

434

Example 3: for
int counter; float total = 0, mark, average;
for (counter=1; counter <= 3; counter++) { cout << Enter mark: ; cin >> mark; total = total + mark; } average = total / 3; cout << Average for 3 quizzes: << average;

sanggagakputih.blogspot.com

435

Example 3: for

sanggagakputih.blogspot.com

436

Example 3:
Sample of Output:

sanggagakputih.blogspot.com

437

Exercise 1 Compute the product of all the numbers from 1 to 8.


(Hint: Use a called product instead of initialize product to 1) variable sum and

sanggagakputih.blogspot.com

438

Exercise 2 Find the sum of the square of all the numbers from 1 to 5.
(i.e. 1*1 + 2*2 + 3*3 +... )

sanggagakputih.blogspot.com

439

Exercise 1 - Answer

sanggagakputih.blogspot.com

440

Exercise 1 - Output

sanggagakputih.blogspot.com

441

Exercise 2 - Answer

sanggagakputih.blogspot.com

442

Exercise 2 - Output

sanggagakputih.blogspot.com

443

8.5 Use of Control Structure

SUMMARY
Write a program segment by using appropriate control structure.

sanggagakputih.blogspot.com

444

CHAPTER 8: PROGRAMMING
8.6 Header File and Functions
8.6.1 Standard Header file 8.6.2 Functions

sanggagakputih.blogspot.com

445

8.6 Header file and Functions


At the end of the lesson student should be able to: 1) use standard header file in a program 2) use appropriate functions in a program

sanggagakputih.blogspot.com

446

Introduction
Header file is a text file containing small

bits of program code, which is used to describe the contents of the main body of code to other modules.

Also known as pre-processor directive. The header file tells the compiler what is

available in the library.

sanggagakputih.blogspot.com

447

8.6.1 Standard header file

The following header files are supplied with the standard libraries: . iostream.h . stdlib.h OR cstdlib.h . time.h OR ctime.h . math.h
http://www.cplusplus.com/reference/clibrary/
sanggagakputih.blogspot.com 448

i) iostream.h input output stream

Declares objects that control reading from and writing to the standard streams.
The only header files to perform input and output in a C++ program. #include <iostream.h>

sanggagakputih.blogspot.com

449

i) iostream.h input output stream


Defines global objects:

sanggagakputih.blogspot.com

450

i) iostream.h example
# include <iostream.h> int main() { cout << My first C++ program; cout << endl; cin.get(); return 0; }
sanggagakputih.blogspot.com 451

i) iostream.h example
#include <iostream.h> int main()

{
char name [30]; cout << Enter Your Name: ; cout << endl; cin >> name; cin.get(); return 0; }
sanggagakputih.blogspot.com 452

i) iostream.h example

sanggagakputih.blogspot.com

453

ii) cstdlib.h (stdlib.h)

Used for testing and converting characters.


This header defines several general purpose functions, including dynamic memory management, random number generation, communication with the environment, integer arithmetic, searching, sorting and converting. #include <stdlib.h>
sanggagakputih.blogspot.com 454

ii) cstdlib.h (stdlib.h)

sanggagakputih.blogspot.com

455

ii) cstdlib.h (stdlib.h)


#include <stdlib.h> #include <iostream.h> #include <time.h> int main( ) { unsigned masa = time(NULL) ; cout<<masa = << masa <<endl ; srand(masa); //Initialize random number generator for (int i=0 ; i<8 ; i++) cout << rand( ) << endl; return 0; }
sanggagakputih.blogspot.com 456

sanggagakputih.blogspot.com

457

Sample of output:

sanggagakputih.blogspot.com

458

ii) cstdlib.h (stdlib.h)

sanggagakputih.blogspot.com

459

iii) ctime.h (time.h)

This header file contains definitions of functions to get and manipulate date and time information. Declares the structure tm, which includes at least the following objects:

int int int int int int

tm_sec seconds [0,61] tm_min minutes [0,59] tm_hour hour [0,23] tm_mday day of month [1,31] tm_mon month of year [0,11] tm_yearsanggagakputih.blogspot.com years since 1900

460

iii) ctime.h (time.h)

sanggagakputih.blogspot.com

461

iii) ctime.h (time.h)

Output:
sanggagakputih.blogspot.com 462

iv) cmath (math.h)

cmath declares a set of functions to compute common mathematical operations and transformations.
#include <math.h>

sanggagakputih.blogspot.com

463

iv) cmath (math.h)

sanggagakputih.blogspot.com

464

iv) cmath (math.h)

sanggagakputih.blogspot.com

465

iv) cmath (math.h) - example

Output:
sanggagakputih.blogspot.com 466

8.6.2 Functions
A function is a sub-program that program can call to perform a task. When you have a piece of code that is repeated often you should put it into a function and call that function instead of repeating the code.

sanggagakputih.blogspot.com

467

8.6.2 Functions Creating your own function


Declare a function in a similar way as create the main function. Here is a function that prints Hello.

void PrintHello() cout << "Hello\n";

{ }
sanggagakputih.blogspot.com 468

8.6.2 Functions Calling a function

Once you have created the function you must call it from the main program. Here is an example of how to call the PrintHello function.
void PrintHello()

cout << "Hello\n";


} int main()

{
PrintHello(); return 0;
sanggagakputih.blogspot.com 469

8.6.2 Functions Calling a function

sanggagakputih.blogspot.com

470

Summary
1) use standard header file in a program 2) use appropriate functions in a program

sanggagakputih.blogspot.com

471

CHAPTER 8: PROGRAMMING
8.7 Simple C++ Program

sanggagakputih.blogspot.com

472

8.7 Simple C++ Program


At the end of the lesson student should be able to: 1) Write a simple C++ program.

sanggagakputih.blogspot.com

473

Das könnte Ihnen auch gefallen