Beruflich Dokumente
Kultur Dokumente
in C & C++
1
What is Programming?
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
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.
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.
Problem Identification
Identify what the problem actually is.
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?
2.1
1.1 1.2 2.2 level 2
Calculate refinement
Get Test Get Exam Check Final
Final
Score Score Score Status
Score
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
5. Run and Debug the program - check if you have the desired
output; if not, trace the possible error.
Flowcharting Guidelines
1. Boil kettle
2. Put tea in cup
3. Pour boiling water
into cup
No
Boil kettle
Display message
“How many
hours did you
work?”
of a program.
The figure shown
Read Pay Rate
in Chapter 1. Pay
END
Basic Flowchart START
Rounded
Rectangle
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
operation.
Basic Flowchart START Terminal
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
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?”
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?”
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?”
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?”
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?”
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?”
Multiply Hours
by Pay Rate.
Store result in
Variable Contents:
Hours: 40
Pay Rate: 20
Gross Pay: 800 Gross 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.
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
1 2 3 Other
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
A
Connectors
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
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
Decision
Terminal
Input/Output
Operation Connector
Process Module
Review
Sequence
Decision
Repetition
Case
Review
What type of structure is this?
Repetition
Review
What type of structure is this?
Sequence
Review
What type of structure is this?
Case
Review
What type of structure is this?
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
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 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
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
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
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
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?
Algorithm
Steps of Problem Solving
Analysis
Algorithm Design
Steps of Problem Solving
Desk check
Programming
Steps of Problem Solving
Testing
Understand the problem
What is the problem?
relationships?