Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
106 views

01 - Programming Problem-Solving

The document discusses the programming process and problem solving techniques, explaining that programming involves gathering input, processing the input, and producing output. It provides examples of writing pseudo code to design algorithms for programs that calculate values like employee taxes and rectangle areas based on given inputs. The document also introduces flowcharts as a way to visually represent algorithms through geometric shapes and connecting lines.

Uploaded by

Aya Amir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
106 views

01 - Programming Problem-Solving

The document discusses the programming process and problem solving techniques, explaining that programming involves gathering input, processing the input, and producing output. It provides examples of writing pseudo code to design algorithms for programs that calculate values like employee taxes and rectangle areas based on given inputs. The document also introduces flowcharts as a way to visually represent algorithms through geometric shapes and connecting lines.

Uploaded by

Aya Amir
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 114

01: PROGRAMMING PROBLEM-

SOLVING
Programming Technique I
(SCSJ1013)
Problem-Solving Process
The Programming Process
Programming Process

 Programming is a process of problem solving.

 Problem solving techniques


 Outline the problem requirements
 Analyze the problem
 Design steps (algorithm) to solve the problem
Programming Process

This week
Input, Process and Output
Input, Process and Output

Three steps that a program typically performs:

 Gather input
 from keyboard
 from files on disk drives

 Process the input

 Display the result as output


 send it to the screen
 write to a file
Example 1
 Identify an input, process and output to develop a program
to calculate area of a rectangle.

 Input data
 Length
 Width
 Process the input
 Area = Length * Width
 Output Data
 Area
In-Class Exercise 1

Identify the input, process and  Input data


output for a program to calculate  Name
employee income tax based on the  Monthly income
following formula:  Number of kids
 Process the input
 Tax = 0.25 * (Monthly
Tax = 0.25 * (monthly income * income * 11 – Number
11 – number of kids * 450) of kids * 450)
 Output Data
Your program will display the name  Name
of the employee and amount of tax  Tax
on the screen.
In-Class Exercise 2
Identify the following information:
Input data, Process the input data, and Output data

 Do Exercise 2.7, No. 7(a), pg. 56


 Do Exercise 2.7, No. 7(c), pg. 56
 Do Exercise 2.7, No. 7(d), pg. 57
 Do Exercise 2.7, No. 7(e), pg. 57
 Do Exercise 2.7, No. 8, pg. 57
 Do Exercise 2.7, No. 9, pg. 59
Procedural and
Object-Oriented Programming
Procedural and Object-Oriented
Programming
 Procedural programming (a.k.a structured programming) is
centered on procedures or functions (a.k.a modules).
Example language: C.

 Object-oriented programming (OOP), is centered on objects.


An object contains data and procedures. Example language:
C++.
Problem Solving Techniques
Problem Solving Methods
Three problem solving methods will be discussed in this class
are:

 Develop Algorithms
 Flowchart
 Pseudo code

 Top-down design
 Structured Chart
Algorithms
 Algorithm - a sequence of a finite number of steps arranged
in a specific logical order to produce the solution for a
problem.

 Algorithms requirements:
 Must have input
 Must produce output
 Unambiguous
 Generality
 Correctness
 Finiteness
 Efficiency (pg. 32)
Pseudo codes
Pseudo Code

 Pseudocode is a semiformal, English-like language with


limited vocabulary that can be used to design & describe
algorithms.

 Purpose- to define the procedural logic of an algorithm in a


simple, easy-to-understand for its readers.

 Free of syntactical complications of programming language.


Example: Pseudo Code
 Execution sequence follow the steps flow.

Example: Algorithm for


multiplying two numbers
1. Start
2. Get A Execution
3. Get B sequence
4. Calculate result,
C = A * B
5. Display result C
6. End
In-Class Exercise 1
1.Start
Develop a pseudo code for a
2.Get name
program to calculate employee
3.Get monthly_income
income tax based on the following
4.Get num_kids
formula:
5.Calculate tax:
tax = 0.25 *
Tax = 0.25 * (monthly income * (monthly_income *
11 – number of kids * 450) 11 – num_kids *
450)
6.Display name and
Your program will display the name tax
of the employee and amount of tax 7.End
on the screen.
In-Class Exercise 2

Develop a pseudo code:

 Do Exercise 2.7, No. 7(a), pg. 56


 Do Exercise 2.7, No. 7(c), pg. 56
 Do Exercise 2.7, No. 7(d), pg. 57
 Do Exercise 2.7, No. 7(e), pg. 57
 Do Exercise 2.7, No. 8, pg. 57
 Do Exercise 2.7, No. 9, pg. 59
Flowcharts
Flowchart

 Flowchart - represents an algorithm in graphical symbols.

 Flowchart – a graph of geometrical shapes that are


connected by lines.

 Two important element in flow chart:


 Geometrical shapes – represent type of statements in the algorithm
 Flow line – show the order in which the statements of an algorithm
are executed.
Example: Flowchart
Start
 Algorithm for multiplying
two numbers Get A
Get B

Calculate Result
C=A*B

Display the
Result C

Stop
Flowchart Symbol
Flowchart Symbol
Terminal: Used to indicates the start and end of a flowchart. Single flowline. Only one “Start”
and “Stop” terminal for each program. The end terminal for function/subroutine must use
“Return” instead of “Stop”.

Process: Used whenever data is being manipulated. One flowline enters and one flowline exits.

Input/Output: Used whenever data is entered (input) or displayed (output). One flowline enters
and one flowline exits.
Decision: Used to represent operations in which there are two possible selections. One flowline
enters and two flowlines (labelled as “Yes” and “No”) exit.

Function / Subroutine: Used to identify an operation in a separate flowchart segment (module).


One flowline enters and one flowline exits.

On-page Connector: Used to connect remote flowchart portion on the same page. One flowline
enters and one flowline exits.
Off-page Connector: Used to connect remote flowchart portion on different pages. One flowline
enters and one flowline exits.

Comment: Used to add descriptions or clarification.

Flowline: Used to indicate the direction of flow of control.


(pg. 39)
Flowchart Explanation
Start Start Terminal.
Program start here

Get A
Input.
Get B Enter values for A and B

Calculate Result
Process.
C=A*B

Display the
Output
Result C

Stop Terminal
Stop Program end here
Example: Use of comments/
description
Start

Read N, N = The number of students


M M = The number of subjects

Yes

No
Stop
Example: Use of connectors on the
same page
Start 2
1

1- connection on the same


flowchart portion
2- connection on the different
Stop flowchart portion
Yes
1

No

2
Example: Use of connectors on the
different page
Page 1 Page 2
Start
2
1

Yes Stop
1

No

2
In-Class Exercise
Start

Draw a flowchart for a program to


calculate employee income tax Get Name,
Monthly_income,
based on the following formula: num_kids

Calculate Tax = 0.25 *


Tax = 0.25 * (monthly income * (Monthly_income * 11 –
11 – number of kids * 450) num_kids * 450)

Display the
Name and Tax
Your program will display the name
of the employee and amount of tax
Stop
on the screen.
Flowchart Structures
Control Structure

 Describe the flow of execution

 Basic types of control structure:


 Sequential
 Selection
 Repetition
Flowchart Structures: Sequential
Sequential Structure
 A series of steps or statements that are executed in the order
they are written in an algorithm.

 Pseudo code - Mark the beginning and end of a block of


statements.

1. Start
2. Statement_1
3. Statement_2
4. Statement_3
: :
n. Statement_n
n+1. End
Sequential Structure: Flowchart

 Multiple statements considered as one statement.

Statement simply means


command or instruction
statement

 statement
statement
Flowchart Tracing
Start

Read Input:
Length, Length = 5
Width Width = 3

Calculate Area
Process:
Area = Length * Width
Area = 5 * 3 = 15

Calculate Perimeter Process:


Perimeter = Perimeter =
2 * (Width + Length) 2* (5+3) = 16

Print Output
Area, Area = 15
Perimeter Perimeter = 16

Stop
Trace Table
 Trace tables allow developers to test their algorithms in order
to make sure there are no logic errors.

 Within the trace table, each variable, conditional test and


output must be listed.

 Example:

Length Width Area Perimeter Output

10 15 150 50 Area = 150, Perimeter = 50

20 20 400 80 Area = 400, Perimeter = 80

30 15 450 90 Area = 450, Perimeter = 90


In-Class Exercise 1
Trace the content of the variables and determine the output of
the following algorithm, if the input for Radius is:
a. 3 b. 10 c. 150

Algorithm 1: Compute the area of a circle


1. Start
2. Set PI = 3.14159
3. Read the Radius
4. Calculate the area of a circle using the
formula:
Area = Radius x Radius x PI
5. Display Area
6. End
In-Class Exercise 2

Execute the flowchart using Start

the following input values:


Read N
a. 89
True
b. 26 (N % 2) = = 0 N is even
number
c. 0 False

d. 3 N is odd
number

End
Flowchart Structures: Selection
Selection Structure
 Selection allows you to choose between two or more
alternatives; that is it allows you to make decision.

 Decisions made by a computer must be very simple since


everything in the computer ultimately reduces to either true
(1) or false (0).

 If complex decisions are required, it is the programmer’s job


to reduce them to a series of simple decisions that the
computer can handle.
Selection Structure: Problem
Examples
• Problem 1: Determine whether profit, return capital or loss.

• Problem 2: Determine whether a number is even or odd.

• Problem 3: Determine whether the marks is less than 60%. If


it is less than 60, then print “fail”, otherwise print “pass”.

• Problem 4: Determine whether the speed limit exceeds 110


km per hour. If the speed exceeds 110, then fine = 300,
otherwise fine = 0. Display fine.
• Problem 5: Determine whether the age is above 12 years old.
If the age is above 12, then ticket = 20, otherwise ticket = 10.
Display ticket.
Selection Structure (cont..)

• Pseudo code – requires the use of the keywords if.

Algorithm: one choice selection


:
n. if condition
n.1 statement
n+1. end_if
:
Selection Structure (cont..)
If
“do or don’t”
(one-choice)

TRUE
condition
condition

FALSE

statement
 statement

If set condition is true, execute the statement,


else do nothing
Example

 Determine whether an input number is even. If the number


is even, print “This is even number”.
Pseudocode

1. Start
2. Read n
3. If n modulus 2 == 0
1. Print “This is an even number”
4. End if
5. End
Flowchart
Start

Read n

n%2=
0

True
False
Print “this
is an even
number”

End
Selection Structure
(cont..)
• Pseudo code – requires the use of the keywords if and
else.

Algorithm: two choices selection


:
n. if condition
n.1 statement
:
n+1. else
n+1.1 statement
:
n+2. end_if
:
Selection Structure (cont..)
If-else
(two-choices) “do this or do that”

TRUE FALSE
condition

Statement 1 Statement 2  statement

If set condition is true, execute the first


statement, else execute second statement
Example

• Determine whether an input number is even


or odd. If the number is even, print “This is
even number”. Else, print “This is odd
number”.
Pseudocode
1. Start
2. Read n
3. If n modulus 2 = 0
1. Print “This is an even number”
2. Go step 6
4. Else
1. Print “This is an odd number”
5. End if
6. End
Flowchart
Start

Read n

n%2=0

False
True

Print “this Print “this


is an even is an odd
number” number”

End
Selection Structure –
Problem Examples
 Used to compare numbers to determine relative order

 Operators:

> Greater than


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

 Boolean expressions – true or false

 Examples:

12 > 5 is true
7 <= 5 is false
if x is 10, then
x == 10 is true,
x != 8 is true, and
x == 8 is false
Logical Operators
 Used to create relational expressions from other relational
expressions

 Operators, meaning, and explanation:

&& AND New relational expression is true if both


expressions are true
|| OR New relational expression is true if either
expression is true
! NOT Reverses the value of an expression – true
expression becomes false, and false becomes
true
Truth Table

AND (&&) OR (||)


P Q P && Q P Q P||Q
T T T T T T
T F F T F T
F T F F T T
F F F F F F
Logical Operators -
examples
int x = 12, y = 5, z = -4;
(x > y) && (y > z) true

(x > y) && (z > y) false

(x <= z) || (y == z) false

(x <= z) || (y != z) true

!(x >= z) false


Example:
What is the output of the following flowchart when the input Num= 10

Start
Enter a Number >> 10

Category A
Input:
Read Num
Num <- 10

Num = 10
10 > 0 ? => YES

Num>0? No

Print
"Category B"
Yes

Print
Output:
"Category A"
“Category A”

Stop
Example:
What is the output of the following flowchart when the input is Num= 0

Start
Enter a Number >> 0
Input:
Num <- 0
Category B
Read Num Category A
Num = 0 Output:
0 > 0 ? => NO “Category B”

Num>0? No

Print
"Category B"
Yes

Print
Output:
"Category A"
“Category A”

Stop
Example:
What is the output of the following flowchart when the input Num= 4

Start Variables
Variables
Variables (in
(in
(inmemory):
memory):
memory):

Num
Num
Num [[[ 444 ]]]
Read Num Input: Result
Result
Result [[[ 4
0710]
9 ]]] 0497 +++ 4312
Num <- 4 Count
Count [[[ 3
Count 420
1 ]]] 4312 --- 111

Initialize

Result=0
Count=Num

Enter a Number => 4


Count
Count
Count=
Count ===4
132
0
Print Count Count: 4
4
132>
>>>0
000?? ??=>
=>
=>YES
YES
YES
0 => YES
NO Count: 3
Count: 2
Result=Result + Count
Count>0? Yes Count: 1
Count=Count - 1
Count: 0
No
Result: 10

Print
Result

Stop
In-Class Exercise
Start

Read itemName, What will be the output for


tagcolor, price the following input?
Book Green 350.00
tagcolor == “Red”
&& price > 100.00 Curtain Red 500.00
False
True nettprice = price
tax = 10%

nettprice = price - tax

Print
itemName,
nettprice

End
In-Class Exercise 2
• Write a pseudo code for a program that will
accept 2 numbers. If the first number is greater
than the second number, find the difference
between the numbers and print the numbers and
difference value. If the second number is greater
than the first number, find the sum of the two
values and print the numbers and the sum.
• Draw the flowchart for the pseudo code.
• Trace the algorithm with the following input.
Write the output: 40 50
70 30
In-Class Exercise 3

• Write down an algorithm (pseudo code) and


draw a flowchart to read two numbers. If the
first number is greater than the second
number and it is larger than 50, find the sum
and print the sum. Else, print the difference.

• Verify your result by a trace table. (Use 52, 30


as the numbers read)
Selection Structure (cont..)
• Pseudo code – nested if.

Algorithm: nested if
:
n. if condition
:
n.m if condition
n.m.1 statement
:
n+1. end_if
:
Selection Structure (cont..)
Nested if
(if within if)

FALSE
test1 FALSE
test1
TRUE
TRUE
FALSE

TRUE
test2

statement

Considered as
one statement

it is an “one-choice” if
Selection Structure (cont..)
• Pseudo code – nested if using if-else if.

Algorithm: if-else if
:
n. if condition
n.m if condition
n.m.1 statement
:
n+1. else
n+1.m.1 statement
:
n+2. end_if
:
Selection Structure (cont..)

Complex if-else & if Statements

FALSE
condition
TRUE

statement

statement TRUE
condition

FALSE
statement

Considered as one statement


Selection Structure (cont..)
• Pseudo code – nested if using if-else if- else if - else.

Algorithm: if-else if – else if -


else
:
n. if condition
n.m statement
n+1 else if condition
n+1.1 statement
:
n+2 else if condition
n+2.1 statement
n+3 else
n+3.1 statement
n+4 end_if
:
X

T
condition
statement

T
condition statement

T
statement condition

statement
In-Class Exercise 1
• Suppose we want to associate noise loudness
measured in decibels with the effect of the
noise. The following table shows the
relationship between noise levels and human
perception of noises. Draw a flow chart.

Loudness in decibels (db) Perception


50 or lower Quiet
51-70 Intrusive
71 – 90 Annoying
91- 110 Very annoying
Above 110 uncomfortable
In-Class Exercise 2
• Write a pseudo code for nested if as illustrated
in the flow chart below:
pH >
7
true
pH<12
pH==7
false true
“neutral”
false “Very “alkaline”
true alkaline”
pH>2 “Acidic”

false

“Very
acidic”
In-Class Exercise 3
• Write a pseudo code and draw a flow chart for
a program that will implement the following
decision table. The program will print the
transcript message based on the input grade
point.
Grade Point Average Transcript Message
0.0 – 0.99 Failed
1.0 – 1.99 On probation
2.0 – 2.99 Average
3.0 – 3.49 Dean’s List
3.5 – 4.00 Highest Honors
Flowchart Structures: Repetition
Repetition Structure

 Specifies a block of one or more statements that are


repeatedly executed until a condition is satisfied.

 Usually the loop has two important parts:


 An expression that is tested for a true/false,
 A statement or block that is repeated as long as the expression is
true

 2 styles of repetition or loop


 Pre-test loop
 Post test loop
Repetition Structure -
Counters

• Counter: Can be used to control execution of the loop (loop


control variable)

• It will increment or decrement each time a loop repeat

• Must be initialized before entering loop


Repetition Structure:
Pre-Test Loop
• Pseudo code – requires the use of the keywords while for pre-test
loop.

Algorithm: one choice selection


:
n. while condition
n.1 statement
:
n+1. end_while
:
Repetition Structure
(cont..)
while Loop
(pre-test loop)

FALSE
condition
condition

TRUE  statement
body of loop

While a set condition is true, repeat statement (body


of loop)
Repetition Structure
(cont..)

x
Start

initialization
cnt = 0
°
FALSE
FALSE
condition
cnt < 5 End
TRUE
TRUE
body of loop
Print “Programming”

increment
cnt = cnt + 1
y
Pre-test loop steps summary

 Counter-controlled loop
 Initialization of counter: counter = 0
 Testing of counter value: counter > n
 Updating of counter value (increase by 1) during each iteration:
counter = counter + 1
Example

 Suppose we want to write a program to compute a sum of


the first 10 positive integers.

 Steps:
 How many repetition?
• Initialization
• Condition to check for the counter?
• Update of counter
Pseudo code

1. Start
2. Set sum=0, counter = 0
3. While (counter < 10)
3.1 sum = sum + counter
3.2 counter = counter + 1
4. End_While
5. Display sum
6. End
Flow Chart
Start

sum = 0, counter = 1

false
counter print sum
< 10
true

sum = sum + counter End

counter = counter + 1
Trace the following
Start

sum = 0, counter = 0
What is the output for the
following input:
false
counter print 20 30 40 50 10
<5 sum
true
read n
End

sum = sum + n

counter = counter+1
Repetition Structure:
Post-Test
• Pseudo code – requires the use of the keywords repeat..until for
post-test loop.

Algorithm: one choice selection


:
n. Do
n.1 statement
:
n+1. While condition
:
Repetition Structure
(cont..)
do-while Loop
(post-test loop)

statement
 statement

condition
TRUE
FALSE

• Do the statement (body of loop) while a condition is true.


• The loop body is executed at least once.
Example

1. Start
2. Set sum = 0, counter = 0
3. do
3.1 sum = sum + counter
3.2 counter = counter + 1
4. while (counter < 10)
5. Display sum
6. End
Flow Chart
Start

sum = 0, counter = 0

sum = sum + counter

true
counter = counter + 1

false print sum


counter < 10

End
In-Class Exercise 1
• Develop an algorithm (pseudo code) and flow
chart for a program to calculate an average of
15 numbers input by the user. Use pre-test
loop
• Modify your solution above by using the post-
test loop.
In-Class Exercise 2
• Develop an algorithm and flow chart to print
even numbers between 1 to 50. Use pre-test
loop.
• Modify your solution by using post-test loop.
Repetition Structure -
Letting the User Control a Loop
• Program can be written so that user input determines loop
repetition.

• Used when program processes a list of items, and user


knows the number of items

• User is prompted before loop. Their input is used to control


number of repetitions
Repetition Structure (cont..)

Start

cnt = 0

Get limit

FALSE
cnt < limit End

TRUE
Print “Radziah”

cnt = cnt + 1
Repetition Structure -
Sentinels

• sentinel: value in a list of values that indicates end of data

• Special value that cannot be confused with a valid value, e.g.,


-999 for a test score

• Used to terminate input when user may not know how many
values will be entered
Repetition Structure -
Sentinels

Algorithm: Loop control by sentinel value


1. Start
2. Set repeat = 1
3. while (repeat == 1)
3.1 Read no1
3.2 Read no2
3.4 Print no1 + no2
3.5 Read repeat
4. end_while
5. End
In-Class Exercise 1
Trace the following pseudo code:
1. Start
2. Set product = 1, number = 1, count = 20
3. Calculate: lastNumber = 2 * count – 1
4. while (number <= lastNumber)
4.1 product = product * number
4.2 number = number + 2
5. end_while
6. Display product
In-Class Exercise 2
• Convert the pseudo code in In-Class Exercise 1
to its flow chart.
• Convert the while loop in In-Class Exercise 1 to
do..while loop. Draw its respective flow chart.
In-Class Exercise 3
• Bina Education Sdn. Bhd. wants you to develop a
program for finding experience teachers for its offered
course. Your program will request name and number of
years teaching from the applicants. To be accepted as the
teacher, the applicant must have at least 8 years of
teaching experience. Your program will display list of
successful applicants’ names, numbers of successful
applicants and average of numbers of years of teaching
experience of successful applicants. Your program will
terminate when the name input is “OK”.
Modular Flowcharting
The detail of how the function works
Function is put in another flowchart.

Problem: To average three numbers This is known as Function-Definition

Page 1 Page 2
Start terminal for a
Start Function is different.

AVRG (n1, n2,n3)

Read
n1, n2 , n3
sum = n1+
n2+n3
result = AVRG (n1, Body of a function is
the same with
n2, n3) main flowchart

At this point,
we only focus on what
result = sum/3
to do. How to do it,
it comes later. Print
result
This part is known as
Function-Call Return result

Stop
End terminal
must be a “Return”.
“result” is the output

Flowchart AVRG calculates the average of three numbers


Problem: To sum and average three numbers
Page 1 Page 2

Start
AVRGSUM (n1,
n2,n3)
Read
X, Y , Z
sum = n1+
n2+n3
(S,A)= AVRGSUM
(X,Y,Z )

Input: n1,n2 and n3


Output: S and A
average = sum/3
Print
S,A
Return sum, average

Stop The function returns


two output, “sum” and
“average”

Flowchart AVRGSUM calculates the total


and average of three numbers
Parameters used in a function-definition
Related Terms and Concepts are called formal parameters

Actual and Formal Parameters a, b, c are formal parameters


Page 1 Page 2

AVRG is the function name Start


Objects enclosed by ( ) – result, AVRG (a,b,c)
n1, n2, n3 - are called parameters

Read
n1, n2 , n3
sum = a+b+c

result = AVRG
(n1,n2,n3)
Each formal parameter represents
an actual parameter according
to its order: R = sum/3
a represents n1,
Print b represents n2,
Parameters used in a function-call result c represents n3
are called actual parameters
The name of an actual parameter
Return Rmay be
result, n1, n2, n3 are actual parameters different from its formal parameter

Stop

Flowchart AVRG calculates the average of three numbers


Only refer to variables that exist in the In a function-definition, you should only
use formal parameters : a, b, c
current chart
Page 1 You shouldn’t usePage
actual
2 parameters

Start
AVRG ( a,b,c)

Read
Wrong!
n1, n2 , n3
n1, n2, n3
can only be sum = n1 + n2
referred to + n3
in the main
result = AVRG (n1, flowchart.
n2,n3)

R = sum/3

Wrong! Print
R can only be R
referred to
in flowchart Return R
AVRG.

Stop
A function may be called several times
Page 1 Page 2

Start
AVRG (a, b,c)
Read
n1, n2 , n3

A function may be Read


called several times n4, n5 , n6 sum = a+ b+c

average1 = AVRG (n1,


n2, n3 ) At this time:
a represents n1,
average2 = AVRG (n4, b represents n2,
n5, n6 ) c represents n3 R = sum/3

result = (average1 +
average2) / 2 Now:

a represents n4, Return R


Print
result b represents n5,
c represents n6

Stop
Function definition:

x and y act as both input and output


An input parameter may also be an output parameters
Page 1 Page 2

Start EXCHG( x, y)

Read hold = x
p, q

x=y

EXCHG (p, q)
y = hold

Print Return
p, q

Function call:

Stop p and q act as both input and output


parameters.

Flowchart EXCHG exchanges or swaps the value


of x and y each other
Example:
What is the output of the following flowchart when the input N = 6
10
Page 1 Page 2 5
average

Start
N=6
AVRG ( n1, n2, n3)

Read
N Sum = 10 + 5 + 6

sum = n1+ n2+n3

average = AVRG (10, 5, N) average =


21/3

result = sum/3

Print
average Output:
Average: 7
Return Result

Stop
What you have learnt so far ….

•Analysis:
-Understanding the problem

•Design:
- Developing algorithm
- Understanding how a flowchart works
- Constructing flowcharts
The next step is implementation (coding)

Coding is a process of converting flowchart


to programming code

Before you can start doing this, you should learn


some basics including the language itself
Writing a C++ Program is a systematic task

Problem

Flowchart

Intermediate code
-prepare a rough code-

Complete code
- add details -
The conversion process is straight forward
Example: multiplying two numbers
Intermediate C++ code

Start void main ()


{

Read A
cin >> A;
Read B

cin >> B;
C = A * B;
Calculate Result
C=A*B cout << C;

}
Display the
Result C

However, the program is still unable to run


Stop
It is not complete yet. We refer this code is as
an intermediate code.
You will get these errors

Error 1: Undefined symbol ‘cin’


The compiler doesn’t recognize the ‘cin’

Error 2: Undefined symbol ‘A’


The program is trying to use a variable A but has
never been registered. Compiler doesn’t
recognize the variable
Fixing the errors and completing the program

This line will help the compiler to recognize


symbols ‘cin’ and ‘cout’. File
iostream.h contains the information of
those symbols and some others.

This tells to register (declare) variables.


Compiler only recognizes registered
variables.

You may notice some extra things.


These are called prompts. They used to let
the user knows what is going on while
the program is running
Example

Problem: Finding the average of three numbers


Flowcharts:

Start
Average(a, b, c)

Read
n1, n2 , n3 sum = a + b + c

avrg = Average(n1, n2, n3) result = sum / 3

Print Return result


avrg

Stop
Intermediate code of the main flowchart
Preparing the rough code

Start void main ()


{
cin >>n1;
cin >>n2;
Read cin >>n2;
n1, n2 , n3
avrg = Average(n1, n2, n3);

cout << avrg;


avrg = Average(n1, n2, n3)

Print
avrg

Stop
Intermediate code of the function flowchart
Preparing the rough code

Average(a, b, c)
Average(a, b, c) {

sum = a + b + c;

sum = a + b + c
result = sum / 3.0;

return result;
result = sum / 3 }

Return result
The complete code
Adding details to the rough code. The details are shown by
bold texts
#include <iostream>
Using namespace std;

float Average(int a, int b, int c)


{ float sum;

sum = a + b + c;
result = sum/3.0;
return result;
}

int main ()
{
int n1;
int n2;
int n3;
float avrg;

cout <<"Enter three numbers: ";


cin >> n1;
cin >> n2;
cin >> n3;

avrg = Average(n1,n2,n3);

cout << "The average is " << avrg;


return 0;
}

You might also like