Sie sind auf Seite 1von 148

Programming

in C & C++

1
What is Programming?

 Program: A set of instructions


written in a computer language
to be carried out by a computer.

 Program execution: The act of


carrying out the instructions
contained in a program.
Learning a Programming Language

 Just like learning any new language


 syntax: “new words”
 grammar: how to put them together
 programming: telling a coherent story
 library: use plots already written

 Initially needs efforts, but pays off in the


end !

3
Programming is like Legos…
Programming Languages
Overview
• Computer programs are written in programming languages.
• If a program contains even a very small error, the computer
cannot understand it.
• A programming language is an artificial language based on a set
of grammar rules.
• We use a programming language to convert an algorithm into a
computer program to enable the computer to solve the problem.
• There are hundreds of programming languages:
Programming Languages
Generations of Programming Languages
The development of programming languages is classified in "generation".
1GL – machine language
2GL – assembly language
3GL – procedural language
4GL – declarative language

First-generation language (1GL)


• Machine language: a string of 0s and 1s.
• Example, add EAX and EBX registers and store the result back to EAX: 03 C3
• Instructions in machine languages are numbers stored as bytes.
• Can be understood by a computer at once.
• But it is hard to read and understand by us. Difficult to learn.
• Each type of computers understands its own machine language only: machine-dependent.
Therefore, the programs are not portable.
Programming Languages
Second-generation language (2GL)
• Assembly language.
• Stored as text.
• Example: to add EAX and EBX registers and store the result back to
EAX: add EAX, EBX
• Each assembly instruction represents exactly one machine instruction.
• Assembler is needed to convert assembly language programs into
machine code so that they can be executed.
• Each type of computers understands its own assembly language only.
ie. also machine-dependent.
Programming Languages
Third-generation language (3GL)
• Also called Procedural language:
solves a problem by executing a sequence of steps (ie. how).
• Examples: Java, C, Pascal

Fourth-generation language (4GL)


• Also called declarative language:
specifies what needs to be done without going into the details.
• Often used to access databases.
• Example: Structured Query Language (SQL)
SELECT * FROM RECORDS WHERE NAME = "CHAN"
Programming Languages
Low-level and High-level Programming Languages
Programming languages can also be classified as high-level and low-level.

Low-level programming languages: Machine language and Assembly language

High-level programming languages: 3GL and 4GL


• Instructions are English-like.
• A single instruction can be written to define many operations at the machine level.
• Converted to machine languages before they can be executed.
• Machine-independent.
• Example: the same C program can be compiled to run in
(1) Personal computer running windows XP – using the compilers provided by some
programming software like the Borland C and Microsoft Visual Studio etc..
as well as
(2) Unix machine – using the Unix C compilers (eg. gcc, cc)
Programming Languages
3 types of translators: Assembler, Compiler, and Interpreter
• Computers can only read their machine languages, so translators are required to convert
programs into machine codes.

Assembler:
• A special program that reads a text file with assembly instructions and converts them into
machine codes.
Compiler:
• A special program that converts the statements written in a high-level programming language
and turns them into machine codes.
• Typically, we type program code using an editor (eg. Microsoft Visual Studio).
The editor often has an Integrated Development Environment (IDE), which contains a compiler.
• The file written by the programmer is called the source program.
circle
• A program may be composed of several source programs, eg. each stores some.c,functions.
square.c, etc.

Each source program is compiled to form an object file (containing the machine codes).
The object files are then linked to form the final executable file.
circle.obj, square.obj, etc
The whole process is called building (including compilation and linking). .
shape.exe
Programming Languages
Interpreter
• A special program that translates and executes each source statement at run-time,
before translating and executing the next statement.
• Example: the web page browsers.
• A program that relies on an interpreter to translate and run is called a script.
The language is called scripting language.

Advantage of using interpreters (eg. for html / javascript)


• After typing the source code, we can run the program at once.
Do not need to compile the whole source code into an executable file first.
• If the language is recognized by webpage browsers, then it is very portable.

Advantage of using compilers (eg. for c, c++, java)


• No source program is required during the execution of the program.
(We need not pass the source code to the user)
• The program needs to be translated once only. Then it can be executed again and again.
• Execution time is shorter (no translation is needed during run-time).
• Syntax errors (eg. typing mistakes) are checked already during compilation.
Less run-time mistakes will be made.
Compiler & Interpreter
 Compiler is a specific software that gets the
whole Source Code (Computer program written in
human understandable form) and translates it into
Object Code (Computer Program that is in
machine understandable form) all at a time.

 Interpreter is translating and executing one


statement (command of Computer Program) of
Source Code into Object Code at a time. (It
means, interpreters translate and execute
computer programs line by line).
Execution of a Program.
Using Compiler:

Object Code
Source Code Compiler

ExecuteProgram
Execute Program
Using Interpreter:

Executeaaline
Execute line
Source Code Interpreter ofProgram
Program
of
Types of Programs
 There are two categories of programs.
 Application programs (usually called just
"applications") are programs that people use to get their
work done.

 Systems programs keep all the hardware and software


running together smoothly. It helps in developing
application programs.
Application Programs Systems Programs

 Word processors  Operating system.


 Game programs  Networking system.
 Spreadsheets  Database system.
 Data base packages  Compilers
 Graphics programs  Web site server.
 Web browsers  Data backup.
Problem Solving Concepts
If a complicated task is to be handled by programming, we need a
systematic way of problem solving.
Example: update all patient records and print their reports
• a lot of data
• a lot of calculations
• a lot of results to check
 easy to get lost or miss out some jobs

• Step by step of development of a program:


• Keep track of what we have done
• Keep track of what we are doing
• To know what we still have to do

• In addition, we need to pay attention to debugging and maintaining a program.


• The one who debugs and maintains the program may not be the one who develops it.
• Therefore, a program developed in a systematic way can help to make debugging
maintenance easy afterwards.
Problem Solving Concepts
Problem Solving Procedures:

Problem Identification
Identify what the problem actually is.

Problem Analysis Break down the problem into subproblems.

Algorithm Design Design the step-by-step procedures of solving a


problem.

Program Development Implement the algorithm as a computer


program.

Debugging and Testing Find out and remove all possible errors in the
solution.
Documentation
Prepare documents that describe the solution.
Problem Solving Procedures
1. PROBLEM IDENTIFICATION
To clarify and define the problem so that we know exactly what should be done.
Example: Check whether a student passes a subject, based on the rule:
The final mark (exam + test, weighed 70% and 30%) should be at least 40.

What is the
problem? What do we
need to
solve?

What Does any


should the constraint affect
program the solution of the
provide? problem?
Problem Solving Procedures
2. PROBLEM ANALYSIS
• For a complicated problem, it is difficult to solve as a whole.
Therefore we need to analyze the problem and break it down into smaller parts.
• Basically to find out the inputs, outputs, and processing of the problem.
• Stepwise refinement is a common problem analysis method of breaking down a problem
level-by-level.
Example:  The problem is divided
First level refinement: to more easily handled
1. Get scores sub-problems,
2. Check whether the student obtains a pass or a fail  Each sub-problem can
3. Output result be developed and tested
Second level refinement: one at a time, or even by
1. Get scores different people at the
1.1 Get test score same time.
1.2 Get examination score
2. Check whether the student obtains a pass or a fail
2.1 Calculate the final score
2.2 Check if the final score is sufficient for a pass or not
3. Output result
Problem Solving Procedures
Pass or Fail level 0

1 Get Scores 2 Check Pass/Fail 3 Output Result level 1


refinement

2.1
1.1 1.2 2.2 level 2
Calculate refinement
Get Test Get Exam Check Final
Final
Score Score Score Status
Score

The refinements can also be shown with a structure diagram:


Problem Solving Concepts
4. PROGRAM DEVELOPMENT
After designing the algorithm, we realize the algorithm by practical means – programming.
In program development, lower level refinements (pseudo-codes, detailed structure diagrams,
flowcharts) may be changed or added along.
Top down approach:
• Develop the main code and major functions first.
These code may contain statements that call lower-level functions that do not exist yet.
• The lower-level functions may be developed later.
• At the moment of developing each function,
the requirements are already very clear.
eg. what to pass as parameters and what to return,
what processing is needed (eg. need to check the input number is negative or not).
Bottom-up approach:
• Develop the lower-level functions first so that they are available already when the higher-level
functions are written and need to call the lower-level ones.
• Bottom-up approach is often used when the detailed requirements of each function are obtained
with confidence in the design stage.
Problem Solving Concepts
5. DEBUGGING AND TESTING
• Debugging means detecting, tracing, and correcting errors (bugs) in a program.
• There are 3 types of programming errors:
Syntax error: An error occurs when an instruction that does not follow the syntax rules of the
programming language.
Example: wrong spelling of keywords, eg. if  If
Easy to identify -- the computer just refuses to run the statement and
gives out message about the program statement.
Run-time error: An error occurs only when a program statement is running.
Example: The statement attempts to use a property of an html element
that doesn't exist.
var id="applle";

document.getElementById(id).innerHTML
The statement causing the run-time error may not be the source of
error.
Logic error: An error is caused by the logic design of the program.
Example: Q1 of week 10 lecture exercise (The wrong isPrime
function)
Problem Solving Concepts
6. DOCUMENTATION

Program documentation consists of:


- A user's guide
- A hard copy of a sample test run of the program
- A source program listing
- A concise requirement specification
- Descriptions of problem inputs, expected outputs, formula, special conditions,
processing steps
- Structure diagram / step-wise refinement results
- Pseudocodes or flowcharts
Problem Solving Concepts
6. DOCUMENTATION

Documentation of a program is important. Because:


- We are likely to use the program again sometime in the future.
- We should provide documentation to the client as he or she will
need information about it.
- Other programmers may be assigned to maintain the program or
make additions to it.
- We may eventually discover some errors and need to correct
them.
Algorithm
 Specified sequence of steps that
 accomplish a designated task
 in a finite number of steps

 Representation:
 simple algorithm: flowchart
 complicated algorithm: program
Algorithm building blocks
Start
Start Start
Programming
Action languages support Action
these three
Decision
building blocks
Action
Test
Action Action
Action

Finish
Finish Finish

Sequence Selection Loop


Algorithm

 It is a list of instructions specifying a precise


description of a step by step process that
terminates after a finite number of steps for solving
an algorithm problem producing the correct answer
in the end.

 It is a recipe for solving problems.

 A finite set of an instruction that specifies a


sequence of operation to be carried out in order to
solve a specific problem.
Methods of Specifying
Algorithm
 Pseudocode - specifies the steps of algorithm
using essentially natural language of
superimposed control structure.

 Flowchart - a traditional graphical tool with


standardized symbols. Show the sequence of
steps in an algorithm.
Properties of Algorithm
 Finiteness - there is an exact number of steps to be taken and has
an end.

 Absence of Ambiguity - means that every instruction is precisely


described and clearly specified.

 Sequence of Execution - instructions are performed from top to


bottom.

 Input and Output - defined the unknowns of the problem is


specified and with the expected outcome.

 Effectiveness - the solution prescribed is guaranteed to give a


correct answer and that the specified process is faithfully carried
out.

 Scope Definition - applies to a specific problem or class of problem.


Steps in Program
Development
1. State the problem clearly- a problem cannot be solved
correctly unless it is being understood.

2. Plan and Write the Logical Order of Instructions - the


computer follows the direction exactly at the given sequence.

3. Code the Program - write the programming statements in


the desired language.

4. Enter the program into the computer - key in or type the


statement into the computer.

5. Run and Debug the program - check if you have the desired
output; if not, trace the possible error.
Flowcharting Guidelines

1. The flowchart should flow from top to


bottom

2. If the chart becomes complex, utilize


connecting blocks

3. Avoid intersecting flow lines

4. Use meaningful description in the symbol


Flowcharting Symbols

SYMBOL NAME DESCRIPTION


Defines the starting
TERMINAL and ending point of
a flowchart.
The preparation or
INITIALIZATION initialization of
memory space for
data processing.
The inputting of data
INPUT/OUTPUT for processing, and
printing out of
processed data.
Manipulation of
data(assignments
PROCESS and mathematical
computations)
Flowcharting Symbols
SYMBOL NAME DESCRIPTION
Defines logical
FLOW LINES sequence of the
program. Its points to
the ext symbol to be
performed
Connects to the
ON-PAGE CONNECTOR flowchart to avoid
spaghetti connection
on the same page
Connects the flowchart
OFF-PAGE CONNECTOR on different page to
avoid spaghetti
connection
Process conditions
DECISION using relational
operators. Used for
trapping and filtering
data.
General Rules for flowcharting
1. All boxes of the flowchart are connected with Arrows. (Not lines)
2. Flowchart symbols have an entry point on the top of the symbol with no other entry
points. The exit point for all flowchart symbols is on the bottom except for the Decision
symbol.
3. The Decision symbol has two exit points; these can be on the sides or the bottom and
one side.
4. Generally a flowchart will flow from top to bottom. However, an upward flow can
be shown as long as it does not exceed 3 symbols.
5. Connectors are used to connect breaks in the flowchart. Examples are:
• From one page to another page.
• From the bottom of the page to the top of the same page.
• An upward flow of more then 3 symbols
6. Subroutines and Interrupt programs have their own and independent flowcharts.
7. All flow charts start with a Terminal or Predefined Process (for interrupt
programs or subroutines) symbol.
8. All flowcharts end with a terminal or a contentious loop.
35
Algorithms

 Algorithm = how you go about solving a puzzle; your


solution to a task
 Example: how do you make a cup of tea?

1. Boil kettle
2. Put tea in cup
3. Pour boiling water
into cup

 In programming, you should plan your algorithm


before you start coding
Tea-making program – 1

No

Is kettle full? Fill kettle


Yes

Boil kettle

Put tea in cup Pour boiling water into cup


What is a Flowchart?
START

Display message
“How many
hours did you
work?”

 A flowchart is a Read Hours

diagram that Display message


“How much do
depicts the “flow” you get paid per
hour?”

of a program.
 The figure shown
Read Pay Rate

here is a flowchart Multiply Hours


by Pay Rate.

for the pay- Store result in


Gross Pay.

calculating program Display Gross

in Chapter 1. Pay

END
Basic Flowchart START
Rounded
Rectangle

Symbols Display message


“How many
hours did you
work?”

 Notice there are Read Hours

three types of Display message


“How much do
symbols in this you get paid per
hour?”
Parallelogra
m

flowchart:
rounded rectangles
Read Pay Rate

 parallelograms Multiply Hours
by Pay Rate.
Rectangle
 a rectangle Store result in
Gross Pay.

 Each symbol
Display Gross

represents a Rounded
Rectangle
Pay

different type of END

operation.
Basic Flowchart START Terminal

Symbols Display message


“How many
hours did you
work?”

 Terminals Read Hours

 represented by Display message

rounded rectangles
“How much do
you get paid per
hour?”
 indicate a starting or
ending point Read Pay Rate

Multiply Hours
START by Pay Rate.
Store result in
Gross Pay.

Display Gross
Pay
END

Terminal
END
Basic Flowchart START

Symbols Display message


“How many
hours did you
work?”

 Input/Output Read Hours

Operations Display message


“How much do
represented by
Input/Output
 you get paid per
Operation
hour?”
parallelograms
 indicate an input or Read Pay Rate

output operation Multiply Hours


by Pay Rate.
Display message Store result in
Gross Pay.
“How many
Read Hours
hours did you Display Gross
Pay
work?”
END
Basic Flowchart START

Symbols Display message


“How many
hours did you
work?”

 Processes Read Hours

 represented by Display message

rectangles
“How much do
you get paid per
hour?”
 indicates a process
such as a mathematical Read Pay Rate

computation or variable
assignment
Multiply Hours
by Pay Rate.
Process Store result in
Multiply Hours Gross Pay.
by Pay Rate.
Store result in Display Gross
Pay
Gross Pay.
END
SteppingThrough
Stepping Through START
Output
Operation

thethe
Flowchart
Flowchart
Display message
“How many
hours did you
work?”

Read Hours
How many
hours did
you work?
Display message
“How much do
you get paid per
hour?”

Read Pay Rate

Multiply Hours
by Pay Rate.
Variable Contents:
Hours: ?
Store result in
Pay Rate: ?
Gross Pay: ? Gross Pay.

Display Gross
Pay

END
SteppingThrough
Stepping Through START

thethe
Flowchart
Flowchart
Display message
“How many
hours did you
work?”

How many Input Read Hours

hours did Operation


you work? (User types Display message
40
40) “How much do
you get paid per
hour?”

Read Pay Rate

Multiply Hours
by Pay Rate.
Variable Contents:
Hours: 40
Store result in
Pay Rate: ?
Gross Pay: ? Gross Pay.

Display Gross
Pay

END
SteppingThrough
Stepping Through START

thethe
Flowchart
Flowchart
Display message
“How many
hours did you
work?”

Read Hours
How much
do you get
paid per
Display message
hour?
“How much do
Output you get paid per
Operation hour?”

Read Pay Rate

Multiply Hours
by Pay Rate.
Variable Contents:
Hours: 40
Pay Rate: ?
Store result in
Gross Pay: ?
Gross Pay.

Display Gross
Pay

END
SteppingThrough
Stepping Through START

thethe
Flowchart
Flowchart
Display message
“How many
hours did you
work?”

Read Hours
How much
do you get
paid per
Display message
hour? 20
“How much do
you get paid per
hour?”

Input Read Pay Rate


Operation
(User types Multiply Hours
20) by Pay Rate.
Variable Contents:
Hours: 40
Pay Rate: 20
Store result in
Gross Pay: ?
Gross Pay.

Display Gross
Pay

END
Stepping Through START

the Flowchart
Display message
“How many
hours did you
work?”

Read Hours
How much
do you get
paid per
Display message
hour?
“How much do
you get paid per
hour?”

Read Pay Rate

Multiply Hours
Process: The by Pay Rate.
Store result in
Variable Contents:
Hours: 40
Pay Rate: 20 product of 40
Gross Pay: 800 Gross Pay.
times 20 is
stored in
Gross Pay Display Gross
Pay

END
Stepping Through START

the Flowchart
Display message
“How many
hours did you
work?”

Read Hours
Your gross
pay is 800
Display message
“How much do
you get paid per
hour?”

Read Pay Rate

Multiply Hours
by Pay Rate.
Store result in
Variable Contents:
Hours: 40
Pay Rate: 20
Gross Pay: 800 Gross Pay.

Output Display Gross


Operation Pay

END
Four Flowchart Structures
 Sequence
 Decision
 Repetition
 Case
Sequence Structure
 a series of actions are performed in
sequence
 The pay-calculating example was a
sequence flowchart.
Decision Structure
 One of two possible actions is taken,
depending on a condition.
Decision Structure
 A new symbol, the diamond, indicates a yes/no
question. If the answer to the question is yes, the
flow follows one path. If the answer is no, the
flow follows another path

NO YES
Decision Structure
 In the flowchart segment below, the question “is x
< y?” is asked. If the answer is no, then process A
is performed. If the answer is yes, then process B
is performed.

NO YES
x < y?

Process A Process B
Decision Structure
 The flowchart segment below shows how a
decision structure is expressed in C++ as an if/else
statement.
Flowchart C++ Code

NO YES if (x < y)
x < y? a = x * 2;
else

Calculate a Calculate a a = x + y;
as x plus y. as x times 2.
Decision Structure
 The flowchart segment below shows a decision
structure with only one action to perform. It is
expressed as an if statement in C++ code.
Flowchart C++ Code

NO YES if (x < y)
x < y? a = x * 2;

Calculate a
as x times 2.
Repetition Structure
 A repetition structure represents part of the
program that repeats. This type of structure is
commonly known as a loop.
Repetition Structure
 Notice the use of the diamond symbol. A loop
tests a condition, and if the condition exists, it
performs an action. Then it tests the condition
again. If the condition still exists, the action is
repeated. This continues until the condition no
longer exists.
Repetition Structure
 In the flowchart segment, the question “is x < y?”
is asked. If the answer is yes, then Process A is
performed. The question “is x < y?” is asked again.
Process A is repeated as long as x is less than y.
When x is no longer less than y, the repetition
stops and the structure is exited.

YES
x < y? Process A
Repetition Structure
 The flowchart segment below shows a repetition
structure expressed in C++ as a while loop.

Flowchart C++ Code

while (x < y)

YES x++;
x < y? Add 1 to x
Controlling a Repetition
Structure
 The action performed by a repetition structure
must eventually cause the loop to terminate.
Otherwise, an infinite loop is created.
 In this flowchart segment, x is never changed.
Once the loop starts, it will never end.
 QUESTION: How can this
flowchart be modified so
YES
it is no longer an infinite
x < y? Display x
loop?
Controlling a Repetition
Structure
 ANSWER: By adding an action within the
repetition that changes the value of x.

YES
x < y? Display x Add 1 to x
A Pre-Test Repetition
Structure
 This type of structure is known as a pre-test
repetition structure. The condition is tested
BEFORE any actions are performed.

YES
x < y? Display x Add 1 to x
A Pre-Test Repetition
Structure
 In a pre-test repetition structure, if the condition
does not exist, the loop will never begin.

YES
x < y? Display x Add 1 to x
A Post-Test Repetition
Structure
 This flowchart segment shows a post-test
repetition structure.
 The condition is tested AFTER the actions
are performed. Display x
 A post-test repetition structure always
performs its actions at least once. Add 1 to x

YES
x < y?
A Post-Test Repetition
Structure
 The flowchart segment below shows a post-test
repetition structure expressed in C++ as a do-
while loop.
C++ Code

Display x
do
Flowchart
{
cout << x << endl;
Add 1 to x
x++;
} while (x < y);

YES
x < y?
Case Structure

 One of several possible actions is taken,


depending on the contents of a variable.
Case Structure

 The structure below indicates actions to


perform depending on the value in
years_employed.
CASE
years_employed

1 2 3 Other

bonus = 100 bonus = 200 bonus = 400 bonus = 800


Case Structure

If years_employed = 2, If years_employed = 3,
bonus is set to 200 bonus is set to 400
If years_employed = 1, If years_employed is
CASE
bonus is set to 100 years_employed any other value, bonus
is set to 800

1 2 3 Other

bonus = 100 bonus = 200 bonus = 400 bonus = 800


Connectors
 Sometimes a flowchart will not fit on one
page.
 A connector (represented by a small circle)
allows you to connect two flowchart
segments.

A
Connectors

• The “A” connector


indicates that the second START A

flowchart segment
begins where the first
segment ends.

END
A
Modules
 A program module (such as a function in C+
+) is represented by a special symbol.
Modules

• The position of the module symbol START


indicates the point the module is executed.
• A separate flowchart can be constructed for Read Input.
the module.

Call calc_pay
function.

Display results.

END
Combining Structures
 Structures are commonly combined to create more
complex algorithms.
 The flowchart segment below combines a decision
structure with a sequence structure.

YES
x < y? Display x Add 1 to x
Combining Structures
 This flowchart segment
shows two decision
structures combined. NO YES
x > min?

Display “x is NO YES
outside the limits.”
x < max?

Display “x is Display “x is
outside the limits.” within limits.”
Review

 What do each of the following symbols


represent?

(Answer on next slide)


Answer

 What do each of the following symbols


represent?

Decision
Terminal

Input/Output
Operation Connector

Process Module
Review

 Name the four flowchart structures.

(Answer on next slide)


Answer

 Sequence
 Decision
 Repetition
 Case
Review
 What type of structure is this?

(Answer on next slide)


Answer

 Repetition
Review
 What type of structure is this?

(Answer on next slide)


Answer

 Sequence
Review
 What type of structure is this?

(Answer on next slide)


Answer

 Case
Review
 What type of structure is this?

(Answer on next slide)


Answer

 Decision
Sample Exercises

Sample 1: Write a program that calculates the sum of two input numbers and
display the result.
 
Sample 2: Write a program to calculate the area of a circle and display the
result. Use the formula: A=πr2 where Pi is approximately equal to 3.1416.
 
Sample 3: Write a program that computes the average of three input quizzes,
and then display the result.
 
Sample 4: Write a program that converts the input Fahrenheit degree into its
Celsius degree equivalent. Use the formula: C= (5/9)*F-32.
 
Sample 5: Create a program to compute the volume of a sphere. Use the
formula: V= (4/3)* πr3 where is pi equal to 3.1416 approximately. The r3 is
the radius. Display result.
 
88
Pseudocode & Algorithm
 Example 1: Write an algorithm to
determine a student’s final grade and
indicate whether it is passing or failing.
The final grade is calculated as the average
of four marks.
Pseudocode & Algorithm
Pseudocode:
 Input a set of 4 marks
 Calculate their average by summing and
dividing by 4
 if average is below 50
Print “FAIL”
else
Print “PASS”
Pseudocode & Algorithm
 Detailed Algorithm
 Step 1: Input M1,M2,M3,M4
Step 2: GRADE  (M1+M2+M3+M4)/4
Step 3: if (GRADE < 50) then
Print “FAIL”
else
Print “PASS”
endif
Example

START
Step 1: Input
M1,M2,M3,M4
Input
M1,M2,M3,M4

GRADE(M1+M2+M3+M4)/4
Step 2: GRADE 
(M1+M2+M3+M4)/4
N IS
GRADE<5
Y Step 3: if (GRADE <50)
0
then
PRINT
“PASS”
PRINT
“FAIL” Print “FAIL”
else
STOP
Print “PASS”
endif
Example 2
 Write an algorithm and draw a flowchart to
convert the length in feet to centimeter.
Pseudocode:
 Input the length in feet (Lft)
 Calculate the length in cm (Lcm) by
multiplying LFT with 30
 Print length in cm (LCM)
Example 2
Algorithm Flowchart
 Step 1: Input Lft
START

 Step 2: Lcm  Lft x 30


Input
 Step 3: Print Lcm Lft

Lcm  Lft x 30

Print
Lcm

STOP
Example 3
Write an algorithm and draw a flowchart
that will read the two sides of a
rectangle and calculate its area.
Pseudocode
 Input the width (W) and Length (L) of a
rectangle
 Calculate the area (A) by multiplying L with
W
 Print A
Example 3

Algorithm START

 Step 1: Input W,L


Input
 Step 2: A  L x W W, L

 Step 3: Print A
A LxW

Print
A

STOP
Example 4
 Write an algorithm and draw a flowchart
that will calculate the roots of a quadratic
equation ax 2 + bx + c = 0

 Hint: d = sqrt ( b 2 - 4ac ), and the roots


are: x1 = (–b + d)/2a and x2 = (–b – d)/2a
Example 4
Pseudocode:
 Input the coefficients (a, b, c) of the
quadratic equation
 Calculate d
 Calculate x1
 Calculate x2
 Print x1 and x2
Example 4
START

 Algorithm:
 Step 1: Input a, b, c Input
a, b, c
 Step 2: d  sqrt ( b �b - 4 �a �c )
 Step 3: x1  (–b + d) / (2 x a) d sqrt(b x b – 4 x a x c)

 Step 4: x2  (–b – d) / (2 x a)
x1 (–b + d) / (2 x a)
 Step 5: Print x1, x2

X2 (–b – d) / (2 x a)

Print
x1 ,x2

STOP
DECISION STRUCTURES
 The expression A>B is a logical expression
 it describes a condition we want to test
 if A>B is true (if A is greater than B)
we take the action on left
 print the value of A
 if A>B is false (if A is not greater than
B) we take the action on right
 print the value of B
DECISION STRUCTURES

Y N
is
A>B

Print A Print B
IF–THEN–ELSE STRUCTURE
 The structure is as follows
If condition then
true alternative
else
false alternative
endif
IF–THEN–ELSE STRUCTURE
 The algorithm for the flowchart is as
follows:
If A>B then
print A
else Y
is
N

print B A>B

endif
Print A Print B
Relational Operators

Relational Operators
Operator Description
> Greater than
< Less than
= Equal to
 Greater than or equal to
 Less than or equal to
 Not equal to
Figure 8-2

Finding the largest integer


among five integers
Figure 8-3

Defining actions in FindLargest algorithm


Figure 8-4

FindLargest refined
Example 5
 Write an algorithm that reads two values,
determines the largest value and prints the
largest value with an identifying message.
ALGORITHM
Step 1: Input VALUE1, VALUE2
Step 2: if (VALUE1 > VALUE2) then
MAX  VALUE1
else
MAX  VALUE2
endif
Step 3: Print “The largest value is”, MAX
Example 5
START

Input
VALUE1,VALUE2

Y is N
VALUE1>VALUE2

MAX VALUE1
 MAX VALUE2

Print
“The largest value is”, MAX

STOP
NESTED IFS
 One of the alternatives within an IF–
THEN–ELSE statement
 may involve further IF–THEN–ELSE statement
Example 6
 Write an algorithm that reads three
numbers and prints the value of the largest
number.
Example 6
Step 1: Input N1, N2, N3
Step 2: if (N1>N2) then
if (N1>N3) then
MAX  N1 [N1>N2, N1>N3]
else
MAX  N3 [N3>N1>N2]
endif
else
if (N2>N3) then
MAX  N2 [N2>N1, N2>N3]
else
MAX  N3 [N3>N2>N1]
endif
endif
Step 3: Print “The largest number is”, MAX
Example 6
 Flowchart: Draw the flowchart of the
above Algorithm.
Example 7

 Write and algorithm and draw a flowchart to


a) read an employee name (NAME), overtime
hours worked (OVERTIME), hours absent
(ABSENT) and
b) determine the bonus payment (PAYMENT).
Example 7
Bonus Schedule
OVERTIME – (2/3)*ABSENT Bonus Paid

>40 hours $50


>30 but  40 hours $40
>20 but  30 hours $30
>10 but  20 hours $20
 10 hours $10
Step 1: Input NAME,OVERTIME,ABSENT
Step 2: if (OVERTIME–(2/3)*ABSENT > 40) then
PAYMENT 50 

else if (OVERTIME–(2/3)*ABSENT > 30) then


PAYMENT 40

else if (OVERTIME–(2/3)*ABSENT > 20) then


PAYMENT 30

else if (OVERTIME–(2/3)*ABSENT > 10) then


PAYMENT 20 

else
PAYMENT 10

endif
Step 3: Print “Bonus for”, NAME “is $”, PAYMENT
Example 7
 Flowchart: Draw the flowchart of the
above algorithm?
Example 1

Write an algorithm in pseudocode that 
finds the average of two numbers.
Algorithm 8.1: Average of two
AverageOfTwo
Input: Two numbers
1. Add the two numbers
2. Divide the result by 2
3. Return the result by step 2
End
Example 2

Write an algorithm to change a numeric 
grade to a pass/no pass grade.
Algorithm 8.2: Pass/no pass Grade
Pass/NoPassGrade
Input: One number
1. if (the number is greater than or equal to 60)
then
1.1 Set the grade to “pass”
else
1.2 Set the grade to “nopass”
End if
2. Return the grade
End
Example 3

Write an algorithm to change a numeric 
grade to a letter grade.
Algorithm 8.3: Letter grade
LetterGrade
Input: One number
1. if (the number is between 90 and 100, inclusive)
then
1.1 Set the grade to “A”
End if
2. if (the number is between 80 and 89, inclusive)
then
2.1 Set the grade to “B”
End if
Continues on the next slide
Algorithm 8.3: Letter grade (continued)
3. if (the number is between 70 and 79, inclusive)
then
3.1 Set the grade to “C”
End if
4. if (the number is between 60 and 69, inclusive)
then
4.1 Set the grade to “D”
End if

Continues on the next slide


Algorithm 8.3: Letter grade (continued)
5. if (the number is less than 59, inclusive)
then
5.1 Set the grade to “F”
End if
6. Return the grade
End
Example 4

Write an algorithm to find the largest of a 
set of numbers. You do not know the 
number of numbers.
Algorithm 8.4: Find largest
FindLargest
Input: A list of positive integers
1. Set Largest to 0
2. while (more integers)
2.1 if (the integer is greater than Largest)
then
2.1.1 Set largest to the value of the integer
End if
End while
3. Return Largest
End
Example 5

Write an algorithm to find the largest of 
1000 numbers.
Algorithm 8.5: Find largest of 1000 numbers
FindLargest
Input: 1000 positive integers
1. Set Largest to 0
2. Set Counter to 0
3. while (Counter less than 1000)
3.1 if (the integer is greater than Largest)
then
3.1.1 Set Largest to the value of the integer
End if
3.2 Increment Counter
End while
4. Return Largest
End
8.4

MORE FORMAL
DEFINITION
Algorithm
 Algorithm: an ordered set of unambiguous
steps that produces a result and
terminates in a finite time.
8.5

SUBALGORITHMS
Figure 8-9

Concept of a subalgorithm
Subalgorithms
 The advantages of subalgorithms:
 It is more undersatandable.
 A subalgorithm can be called many times in
different parts of the main algorithm without
rewritten.
Algorithm 8.6: Find largest
FindLargest
Input: A list of positive integers
1. Set Largest to 0
2. while (more integers)
2.1 FindLarger
End while
3. Return Largest
End
Subalgorithm: Find larger
FindLarger
Input: Largest and current integer
1. if (the integer is greater than Largest)
then
1.1 Set Largest to the value of the integer
End if
End
Example
 Assume your are calculating pay at an hourly
rate, and overtime pay(over 40 hours) at 1.5
times the hourly rate.
 IF the hours are greater than 40, THEN the pay is
calculated for overtime, or ELSE the pay is
calculated in the usual way.
Example Decision Structure
NESTED IF/THEN/ELSE
INSTRUCTIONS
 Multiple decisions.
 Instructions are sets of instruction in which
each level of a decision is embedded in a level
before it.
NESTED IF/THEN/ELSE
INSTRUCTIONS
Problem: An algorithm to calculate even numbers between 0
and 99
1. Start
2. I ← 0
3. Write I in standard output
4. I ← I+2
5. If (I <=98) then go to line 3
6. End
Problem: Design an algorithm which generates even numbers
between 1000 and 2000 and then prints them in the standard output.
It should also print total sum:
1. Start
2. I ← 1000 and S ← 0
3. Write I
4. S ← S + I
5. I ← I + 2
6. If (I <= 2000) then go to line 3 else go to line 7
7. Write S
8. End

142
Write algorithm to this problem:
Ramshewak goes to market for buying some fruits and vegetables. He is
having a currency of Rs 500 with him for marketing. From a shop he
purchases 2.0 kg Apple priced Rs. 50.0 per kg, 1.5 kg Mango priced
Rs.35.0 per kg, 2.5 kg Potato priced Rs.10.0 per kg, and 1.0 kg Tomato
priced Rs.15 per kg. He gives the currency of Rs. 500 to the shopkeeper.
Find out the amount shopkeeper will return to Ramshewak. and also tell
the total item purchased.

143
Problem Solving
 How to get the computer solve a problem?

 Describe the steps that the computer


should take in order to solve the problem

Algorithm
Steps of Problem Solving

1. Understand the problem to be solved

Analysis

2. Devise a solution to the problem

Algorithm Design
Steps of Problem Solving

3. Verify that the solution is correct

Desk check

4. Describe the solution using a programming


language

Programming
Steps of Problem Solving

5. Verify that the program does state the


solution correctly

Testing
Understand the problem
 What is the problem?

 What are the inputs?

 What are the outputs?

 What are examples of input output

relationships?

Das könnte Ihnen auch gefallen