C_ITPR111 Introduction to Programming. Learning Outcomes 1.Use, develop and design structured...
-
Upload
jasper-riley -
Category
Documents
-
view
214 -
download
0
Transcript of C_ITPR111 Introduction to Programming. Learning Outcomes 1.Use, develop and design structured...
C_ITPR111Introduction to Programming
Learning Outcomes1.Use, develop and design structured programming methods
2. Use modularization from the chosen programming language
3. Produce appropriate documentation for a given program application.
4. Create and apply appropriate test schedules
Prescribed textbook
Pretorius C. M, Erasmus H. G, Basic Programming Principles. 2nd edition.
Pearson Education. ISBN: 9781775786030
BUT What is Programming
Programming is breaking down a task into small steps
That simple!!!!!!!!!!!!!!!
And programmers think in an unnatural way WOW!!!!
HOW
Consider this example
Put these words in alphabetic order:
apple,zebra,abacus
IF you cant manage ,then this course might soon become one of the worst experiences of your life so far…………….
So what steps were involved
Certainly you did not sit down and draw a plan of how you were going to do it because your mind does not need to.You learned to do it once when you were a child and now it just happens on its own!!!
STEPS Involved
1. You looked through the words for one beginning with “A”
2. If you found a word beginning with “A", put that word at the beginning of the list in your mind
3. Look for another word beginning with “A”
4. If there is one ,compare its second letter with the second letter of the first “A” word
5. If the second letters are different put the two words in alphabetic order using their second letters. If the second letters are the same ,proceed to the third letter and so on
6. Repeat this whole process for “B” and each letter in alphabetic order, until all the the words have moved to the appropriate place
Computers and programming Programmers have to tell the computers what to
do. Computers require these instructions to be precise
and complete in every way As humans we have an incredible brain which lets
us give vague commands and still get the correct answer. Thus, programmers have to learn to think in anunnatural way: they have to learn to take a description of a task
So tells us more about these
programmers……….. Programmers make lots of money. Programming really is fun. Programming is very intellectually rewarding. Programming makes you feel superior to other
people. Programming gives you complete control over
an innocent, vulnerable machine, which will do your evil bidding with a loyalty not even your
pet dog can rival.
Who can be a programmer?
There are a few traits which might indicate that the person would be a programmerLogicalPatientPerceptiveAt least moderately intelligentEnjoys an intellectual challenge*Gender*
What's actually involved in programming?
Write a program. Compile the program. Run the program. Debug the program. Repeat the whole process until the program is finished.
Unit 3
Programming Concepts
Programming TermsENTITY.
–An object or thing that you can describe.
• e.g a student can be described.
• A student has a name ,height ,weight , age
ATTRIBUTES
These are describing factors for an entity
Attributes describe an object or entity features
• E.g name ,height weight are the attributes of student
When completing an enrolment form about yourself, you are the entity and the information you are entering will be the attributes
Programming Terms.Variable: Variable:
A position or location in the memory of the computer where a value can be stored
It’s a variable because the value of the variable changes or varies as processing is done
Visualise it as a box in memory that contains one and only one specific value at anytime
Data type:
A data type is a classification of what kind of data the variables will hold
The attributes are the variables
An entity has attributes,characteristics
Programming TermsThe programmer must provide space for the attributes to be stored.
NB.the programmer refers to these attributes as variables
To store the attributes(variables), it should first be identified (declared)and then allocated a data type(variable type)
Examples
Description Variable Name
Name of employee empName
Price of a care carPrice
Author of a book author
Quantity in stock quantity
Age of a student stAge
Total number of sales totNumSales
Programming Terms
Data Types– Integer: Whole numbers positive or negative e.g 32, -
12, 0
– Real (float): Numbers with fractions e.g 16.35, 0.2, -987.334
– Character: A single letter, number or special character or symbols e.g “M”, “7”, “#”, “!”
– Boolean: True/false,No/Yes,0/1 e.g. Is there a lesson today?Answer Yes. Boolean value Yes/1/True
– String: two or more characters combined e.g. “Rupert”, “Error message”, “ABC” or “123”
Variable names,types and values
Description Variable name Variable type Possible value
Name of student stName String “John Smart”
Number of Books noBooks Integer 234
Price of item price Real number 78.56
Student?(y/n) student Boolean True(or 1)
Code(A-C) code Character “B”
Variable names,types and values complete the table
Description Variable name Variable type Possible value
Colour of dress
Height of a person in meters
Adult?
Age in years
Salary in R/c
Title of a book
Player in a match
Class code(K,L or M)
Name of lecturer
Number of computers
Types of variables Catagories of Variables
The number of days in a year cannot be represented as a constant nor can the number of weeks in a month. (Explain why.)
Type Description Example
Numeric variables used on numbers where calculations should take place.
Integer, Real
Non-Numeric variables
All other variables Character, String, Boolean
Constant Constantis a fixed value that cannot change throughout the entire program
Any data type e.g V.A.T in SA is 14%There are 24 hours in a dayPi is 3.14159
Arrays related variables, arrays hold numerous values but identical data types
Arrays work with index numbers and typically start at zero (0) e.g monthName[0]
Naming Variables
Naming Variables
1.The name must be unique
2.Variable name must be descriptive e.g student grade should be called grade
3.Variable name may not contain spaces but more than one word may be joined eg pages in a book could be bookPages,price of item could be item_Price
4.Variable name can contain letters and numbers eg department 234
5.A variable must start with a letter,it cannot start with a number
6.Variable name may not contain special charaters like #,&,
7.Variable name must be as short as possible while remaining descriptive.
Examples of variables:
age
department23
lastName
Naming Variables
Answer the following:
Do the following variable names comply with the rules?If not give a reason
5th grade
Member of club
Abc
5472
theAddressOfTheCompanyInTswane
grade&mark
Arrays
Defination:An array is a data structure that consists of a number of related variables.The array can hold numerous values but identical data types.An array has a single name A single variable in an array is called an element All the elements in an array are the same data type The position of an element in an array is called an index.
Arrays ExplainedWe want to have an array that stores the names of days in week.So..
The name of this array is weekDays
wekdays contains the names of the 7 days in a week
We declare the variables of this array as : day1,day2.day3,day4,day5,day6,day7
weekDays
Mon
Tue
Wed
Thur
Fri
Sat
Sun
day1
day2
day3
day4
day5
day6
day7
element index 0 element index 1
element index 2 element index3 element index 4
weekDay(0)
weekDay(1)
weekDay(2)
Weekday(3)
Arrays Explained
Day1,day2 day3 ……… are the variables.
They are of the same data type which is String
These variables have the values Mon,Tu,Wed etc
An element is then a single variable that contains a value at a given time
Index/subscript:It is the position of an element in an array.The value of an index is always positive integer or a zero
The index of the first element is always 0 and the index of the last element is (number of elements - 1) see diagram slide 24
Referencing: used to refer to a specific element.Used also to retrieve an individual value from the array.
The name of the array and the index are used.For example weekDay(0) refers to Mon,weekDay(5) refers to
Array ExampleThe names of the months of the year can be stored in a array.Each element is called month and an index is used to retrieve the individual values from the array.Fill in the missing indexes and referencies in this tableIndex Reference Value
January
February
March
April
May
June
July
August
September
October
November
December
Types of arraysOne dimensional array
Consists of one column that contains a number of row elements.
Like the example on slide 24
Two dimensional array consists of a number of rows and columns
One dimensional array two dimensional array
This array show the minimun
Temperatures for the past seven
Days of the week
345326
3 184 225 236 247 196 25This array shows the minimum and Maximum temperatures for the past Seven days.
Two dimensional array
Row zero has minimum and maximum temperatures for day 1 that is 3 and 18.
Row 3 column 0 contains minimum and maximum temperatures for day 4 that is 3 and 24
If the name of the array is temperature,to reference a particular element we specify both the row and the column number:
temperature(2,1)=23
temperature(4,0)=2
Arrays Continued
;
0 1 2 3 4 5
Step 1: Declare arrayarrBucket = new string[6];
Step 2: Place value in a bucketarrBucket[0] = “Marbles”;
Step 3: Retrieve value from bucketsystem.out.println(“The item in the first bucket
is: ” + arrBucket[0]);
The item in the first bucket is Marbles
A two-dimensional array with two rows and nine columns
An array is a data structure that consists of related data items of the same data type
Analysing and solving problem to solve a problem, we need to understand the problem. How do you make sure that you have understood the problem.
According to (Pretorius & Erasmus, 2012) Check the following:
– 1. Read the problem carefully
– 2. Understand what the problem entails
– 3. Only then write down the steps to solve the problem
Algorithm:Is a set of instruction written in a specific sequence used to solve a problem
Three phases of an algorithm:
1.What data you have available- INPUT
2. How the problem is going to be solved- PROCESSING
3. What the required results will be.- OUTPUT
Properties of an algorithm
Every algorithm has a name that describes the function or purpose of
the algorithm. The name of an algorithm starts with an uppercase letter. The last statement or step is always end. The statements or instructions between the name of the algorithm and
the end are called the body of the algorithm. A ~ (tilde) indicates that a comment, which explains the code, will
follow.A comment can be on a separate line or can follow in the same line as an instruction. A comment typically explains difficult code or why you’re including a specific instruction. A comment can be included anywhere in an algorithm.
Display means that a message or the contents of a variable are displayed (shown) on the computer screen.
Enter indicates that data must be entered via the keyboard. Calculation can also be done using equations..
Example
Determine the weekly wage of an employee when the hours he has worked and the hourly rate, are entered by the user.
Answer
CalcWage
display “How many hours did the employee work?”
enter hours
display “What is the rate of pay?”
enter rate
wage = hours * rate
display “The wage = R”, wage
end
Phases of an algorithm
An algorithm is divided into three phases:1. What data you have available to solve the problem,(INPUT)2. How you’re going to solve the problem; what steps you’re going to take, and(PROCESSING)3. What the required result is(OUTPUT)
Input is processed to produce meaningful output
Example Input processing output
Calculate the sum of two numbers and display the result on the screen:
Input: Not available in the problem statement. The user has to supply the numbers.
Processing: Add the two numbers to determine the sum.
Output: The sum as calculated in the processing phase and displayed on the computer screen.
Note the following:
• The value of the numbers must be available before the sum can be calculated.
• It is impossible to display the sum before it has been calculated
Example Input processing output
The manager of a company asks a student to do some part-time work for
which he will be paid by the hour. The student needs to know how many hours he has to work at what rate of pay before he can calculate the final amount he will receive.
INPUT/DATA: hours and the hourly rate of pay.
The input (data) must be processed to give the output (information),which is the amount the student will receive.It is clear that the input (data) is meaningless unless it is processed, becauseif the student knows how much he will receive per hour, but does not knowhow many hours he will work, the pay cannot be calculated! On the otherhand, if the student works for 20 hours but the manager hasn’t told him how
much he will earn per hour, it is also meaningless.
Input/Processing/Output (IPO) chart
Enter the name and age of a learner on the keyboard and display the name and age with a legend – which is an applicable explanation or heading to describe the output – on the computer screen
IPO chart
Input Processing Output
Name Prompt to read input fields name
age Enter input _elds age
Input/Processing/Output (IPO) chart
AlgorithmShowDetails~ This program will enter the name and the age of the learner and
display it on the screendisplay “Provide the name of the learner” ~ Display on new lineenter namedisplay “Provide the age of the learner” ~ Display on new lineenter age
~ Show the details on the screen with appropriate legendsdisplay “The name of the learner is ”, name ~ Display on new linedisplay “The age of the learner is ”, age ~ Display on new line
end
OutPut
Provide the name of the learner John
Provide the age of the learner 18
The name of the learner is John
The age of the learner is 18
Explanation1. Words that follow the ~ sign are not executable because they’re comments
that explain what is happening or going to happen. In this case, the
purpose of the algorithm is explained.
2. The display “Provide the name of the learner” statement means that
something must be shown on the computer screen. In this case, the text
inside the quotes is displayed.
3. The enter name statement causes the computer to show a prompt on the
screen so that the user can use the keyboard to type a name. This name is
stored in the variable called name.
4. The next two statements enable the user to enter the age of a person to
store in the variable called age.
5. The display “The name of the learner is”, name statement displays the
results on the screen as follows − the words in quotes are shown exactly
as given, whereas name is a variable so its content is displayed. The
output is The name of the learner is John. We have now displayed a constant and the content of a variable. 6. The same rules apply to the next statement, which displays The age of the learner is 18.
Example 2 IPO chart
Enter the distance between two trees in kilometres. Calculate and display the distance in metres and then calculate and display the distance in centimetres
Input Processing Output
Prompt to read kilometer
Kilometer meter
Enter kilometremetre centimeter
Calculate metrecentimetre
Calculate centimetre
Display metre
Display centimetre
Example 2 algorithmConvertDistance
~ Convert km to metres and centimetres
display “Please provide the distance in km. ” ~ Display on new line
enterkilometre
~ Do the conversions
metre = kilometre * 1000
centimetre = metre * 100
~ Display the output on one line
displaykilometre, “ km is equivalent to ” , metre, “m and to ”, centimetre, “cm”
end
Example 3
Enter the length and the width of a tennis court in metres, then calculate
and display the perimeter and the area of the tennis court Input Processing Output length Prompt for input fields perim width Enter input fields area
Example 3 AlgorithmCalcTennisCourt
~ Calculate perimeter and area of tennis court
display “Please enter length” ~ Display on new line
enter length
display “Please enter width” ~ Display on new line
enter width
~ Do calculations and display
perim = 2 * (length + width)
area = length * width
display “The perimeter of the tennis court is ” , perim , “ metres”
display “The area of the tennis court is ” , area , “ square metres”
end
Example 3 trace tableThe input data to test this algorithm is length = 30 and width = 10
Instruction Length Width Peri Area OutputDisplay Please enter lengthenter 30Display Please enter widthEnter 10calculate perim 80calculate area 300display
The perimeter of the tennis court is 80 metre display
The area of thetennis court is 300square metres
Example 4Enter two integers on the keyboard and calculate and show the average of
these two integers on the screen.
Input Processing Output
num1 Prompt for num1 and num2 average
num2 Enter num1 and num2
Calculate average
Show average on the screen
Example4 Algorithm
CalculateAverage
~ Prompt for and enter two integers
display “Enter first number” ~ Display on new line
enter num1
display “Enter second number” ~ Display on new line
enter num2
~ Calculate average
average = (num1 + num2) / 2
~ Show average on the screen
display “The average of the two numbers is ” , average ~ Display on new line
end
Example Output
output
Enter _rst number 24
Enter second number 40
The average of the two numbers is 32
Draw the trace table for the above
Example 5Jason works as a part-time assistant in a bookshop and receives
anhourlywage. Enter the number of hours he worked for a specific week, as well as the pay rate per hour. He has to pay R8 towards the recreation club. Calculate and display how much take-home pay he’s earned for the week.
Input Processing Output
hours Prompt for input fields wage
rate Enter hours and rate rate
Calculate wage
Display wage on screen
Example 5
Algorithm
CalcWeeklyWage
~ Calculate and display the weekly wage for Jason
display “Provide number of hours Jason worked” ~ Display on new line
enter hours
display “Provide rate of pay” ~ Display on new line
enter rate
The input data used to test this algorithm: hours worked = 24 and rate of pay = R12.
What is the output?
Draw a trace table?
Example 6 HomeworkProblem Tebogo earns a monthly salary, which she divides at the
beginning of each month into amounts according to her needs. She pays R450 on rent for her room and the remainder of the money is divided as follows: 50% for food, 20% for clothes, 15% for transport, 5% for charity and the remaining amount for pocket money. Enter her monthly salary, which is never less than R1,800, on the keyboard and then calculate and display how much money she has available for the various categories.
Draw the IPO
Write the algorithm
What is the output (given that the monthly salary is R2000)
Draw the trace table
Example 7 Homework
At The Friendly Store, items can be bought individually, in which case the full amount is paid. However, customers can also buy items in bulk packages of 50 or 100, in which case a discount per item applies. There’s a 10% discount per item on bulk packages of 50, and a 12.5% discount per item on bulk packages of 100.
Draw the IPO
Write the algorithm
What is the output (given price of one item is R50)
Complete the trace table
Instruction amtOne amt50 amt100 save1 save2 amt50 amt100 save50 save100 output
Example 8 Homework
At the EAT-A-LOT restaurant, customers dish up their own food and have th plate weighed in kg (2 decimal positions). The total weight of the plate and the food must be entered. The plate weighs 1.05 kg, which is subtracted from the total weight. The customer has to pay R7.35 per 100 g of food, and 14% VAT is added to the total. Display the weight of the food in kg as well as the amount due.
Draw the IPO
Write the algorithm
Practice exercisesIn each case, indicate the variables used, draw an IPO chart and write an algorithm to solve
the problem. Test your algorithm by doing a trace table
1,Enter two integers. Calculate and show the sum, difference and product of these two integers on the screen.
2.Enter the number of rows of chairs in the city hall as well as the number of chairs per row. Calculate and display the total number of chairs in the hall
3.Enter Ridwaan’s height in metres and centimetres. Calculate and display his height only in centimetres (1 metre = 100 centimetres).
4.Enter values of the minimum and maximum temperatures for a givenday, then calculate the average temperature of the day. Show the answer on the computer screen
5.Enter any integer. Calculate double, half, a third and a quarter of the number and show the result on the screen. The data type of the result must be real.
6.Henry rents a trailer to move stock to a store. The basic cost is R200 per day. He also pays a specific amount per kilometre travelled, entered by the owner. The owner also has to enter the kilometresand the number of days that Henry rented the trailer. Determine and show the amount due on the screen.
OPERATORS:
They are used to perform actions in a program. A program task is to : perform calculations make decisions based on the value of one or more variables. compare values and perform a certain action based on the outcome Operators can be divided into Arithmetic Logical.(logical gates) Relational or Comparison
Arithmetic OperatorsThese operators are used to make calculations such as addition,subtraction, multiplication and division. It tells the computer how the data should be processedOperator Description Example Answer
^ Exponentiation 2^3 8
- Negation (Not) -True False
* Multiplication 3* 4 12
/ Division 6 / 3 2
\ Integer Division 36\5 7
Mod Modulus arithmetic 37 mod 5 2
+ Addition 4 + 10 14
- Subtraction 13 – 7 6
NB:the modulas operator returns the remainder of division of two integers
Exercise Calculate the value of x in each of the following
statements:
-X = g -5 + 14 mod h ^ 2, where g = 12 and h = 1
-X = 35 mod y – (z * w + y / 3) + y * w, where w = 5, y = 24, z = 3
◊ Determine whether the expression is true or false:
m + 7 < n – 3 ^ p, where m = 4, n = 16 and p = Provide a detail solution.
Solve:
(6-2)*5+8
6*(4+7)÷22
12+14÷2-4
Logical operators Compare two expressions/variables and returns a Boolean
value.Logical expressions include AND,OR and NOT Logic operators are also called logical gates Logical gates can be combined create important
components of computers, such as the memory registers.
Operator Desciption Example Answer
AND Requires both variables/conditions to be TRUE for the result to be TRUE
True AND FalseTrue ANDTrueFalse AND False
FalseTrueFalse
OR Requires either variable/condition to be TRUE for the result to be TRUE
True OR FalseTrue OR TrueFalse OR False
TrueTrueFalse
NOT Returns TRUE if the variable/condition is FALSE and vice versa
NOT TrueNOT False
FalseTrue
Logical Operators/Logic gates
Logical Operators/Logic gates
A B A.BFalse False FalseFalse True FalseTrue False FalseTrue True True
A B A+BFalse False FalseFalse True FalseTrue False FalseTrue True True
A ĀFalse TrueTrue False
Logical Operators/Logic gates Switching circuits that perform certain simple operations
on binary signals Have one or two inputs Have one output Inputs and output is one bit in size with a value of either 0
(false) or 1 (true) Basic building blocks of computers and all other digital
devices Can be combined to perform useful and more complex
functions.
ExerciseEvaluate the following expressions:D OR K AND NOT S; where D = TRUE, K = FALSE, S = TRUEM > 7 AND D < S ^ 2; where M = 7, D = 8, S = 4NOT F OR E AND D + C = A; where A = 5, C = 12, D = -4, E = TRUE and F = FALSE
Relational operators Comparison operators compare two numeric or two
character values. A numeric value cannot be compared with a character value.
Operator Description Example = Equal to A = 10 > Greater than number > 50 < Smaller than total < 21 <> Not equal to age <> 0 >= Greater &equal to Weight <>35 <= Smaller & equal to SubjectCount <=6
Exercise
Evaluate the following expressions:
A + T <> (A + B) * 4; where A = 4, B = 17 and T = 20
“true” = 30
Program flowcharts The program flowchart (design)illustrates the logic of the
program and gives details on manipulating the data Just as a builder cannot build a house without a properly
drawn plan ,one should never code a program without a proper design(flowchart)
Program flowcharts are constructed with a set of standardised
symbols that make it easier for persons other than the original programmer to read and maintain the program.
For each symbol in flow chart there is corresponding pseudo code statement
Flowcharts A graphical representation of the sequence of
operations in an information system or program.
Program flowcharts show the sequence of instructions in a single program or subroutine.
– shows logic of an algorithm– emphasizes individual steps and their
interconnections– e.g. control flow from one action to the next
Note: Different symbols are used to draw each type of flowchart.
Flowchart SymbolsSymbol Example and Function
TerminatorIndicates the beginning, end or interruption of a program
Process
Represents program instructions that process data
Decision
Y
N Indication branching based on a decision is made
start
stop
gPay=rate*hours
stopEOF
Flowchart SymbolsSymbol Example and Function
For loop Loops through statements
ConnectorRepresents a connection in flow
Off-page connectorUsed instead of the connector when the flow continues to the next page
AB
More Flowchart SymbolsProcess Symbol Pseudocode
Initialisatiom totHours=0
Assignment totHours=totHours+hours
Input statementInput name,hours
Read statement Read name,hours
Output statement Print “my name is Java”
tot Hours=0
totHours=totHours+hours
Input name,hours
Read name,hours
Print”my name is Java”
pseudocode?
What is pseudocode?Structured English (formalized and abbreviated to look like high-level computer language)
Example 1:
Write an Pseudocode 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.
Example 1-Pseudocode
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”
Example 2
Write an pseudocode and draw a flowchart to convert the length in metres to centimeter.
Pseudocode: Input the length in metre (m) Calculate the length in cm (Lcm) by
multiplying m with 100 Print length in cm (LCM)
START
Inputm
Lcm m x 100
PrintLcm
STOP
Print Lcm
Example 3
Write pseudocode 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 Flow chart
START
InputW, L
A L x W
PrintA
STOP
Print A
Example 4 Write pseudocode and draw a flowchart that will
calculate the roots of a quadratic equation
Hint: d = sqrt ( ), and the roots are: x1 = (–b + d)/2a and x2 = (–b – d)/2a
Pseudocode: Input the coefficients (a, b, c) of the quadratic equation
Calculate d
Calculate x1
Calculate x2
Print x1 and x2
Example 4 FlowchartSTART
Inputa, b, c
d = sqrt(b x b – 4 x a x c)
Printx1 ,x2
STOP
x1 =(–b + d) / (2 x a)
X2 = (–b – d) / (2 x a)
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
isA>B
Print BPrint A
Y N
Print A Print B
IF–THEN–ELSE STRUCTURE
The structure is as follows
If condition then
true alternative
else
false alternative
End if
IF–THEN–ELSE STRUCTURE
The pseudocode for the flowchart is as follows:
If A>B then print A
else print B
endif
Example 5 Write an pseudocode that reads two values, determines the
largest value and prints the largest value with an identifying message.
Pseudocode Input VALUE1, VALUE2
if (VALUE1 > VALUE2) then MAX = VALUE1
else MAX=VALUE2
endifPrint “The largest value is”, MAX
Example 5 Flowchart
MAX =VALUE11
Print“The largest value is”, MAX
STOP
Y N
START
InputVALUE1,VALUE2
MAX = VALUE2
isVALUE1>VALUE2
Print“The largest value is”, MAX
Naming Variables The name must be unique The name must be descriptive The name may not contain spaces A name can contain letters and numbers but NOT NUMBERS
ONLY A variable name must start with a letter A variable name may not contain special characters A variable name should be as short as possible Description Name
Name of employee empName
Price of car carPrice
Author of book Author
Quantity in stock Quantity
Age of student stAge
Total number of sales totNumSales
Do the following variable names comply with the rules? If not, give a reason
5thGrademember of club abc5472 theAddressOfTheCompanyInTshwanegrade&mark
Complete the table
Complete the table-naming variablesDescription Variable name Variable type Possible value
Colour of dress
Height of person in metres
Adult?
Age in years
Salary in R/c
Class code (K, L or M)
Number of computers
Name of lecturer
Functions A function is a group of statements that perform a specific
task and returns a value to the part of the programm that called it
The value that is returned can
– Be assigned to a variable
– Displayed on the screen
– Used in a mathematical expression When you want to execute it you call it. NB:instead of having an equation in the main program a
function can be used
Structure of a functionFunction FunctionName(parameterList)
Statements
Statements
Etc
Return value
End function
Example Function to add two numbers
Function sum(num1,num2)
Result=num1+ num2
Return result
End Function
FunctionsA function can be called as part of the calculation in the main program
Example
total= Function sum(firstNumber,secondNumber) + 200
A fucntion can be called as a variable that will store the value of the answer
Example
studTotal=Function sum(firstNumber,secondNumber)
Worked out examplean assignment statement
Write a calling statement to call a function that calculates the sum of two numbers as well as the function to store the answer in a variable called sum.
Calling Statement
Sum= CalcSum(number1,number2)
The function to calculate 2 numbers
Function calcSum(valNumber1,valNumber2)
total = valNumber1,+ valNumber2)
return total
End function
What is happening in the example
Main program
Sum = Function calcSum(number1,number2)
calcSum(valNumber1,valNumber1)Total = valNumber1 + valNumber2
Return total
End function
function
What is happenning in the examplenumber1 and number2 are the arguments(value
parameters)In the main program the answer will be stored in sum valNumber1 and valNumber2 are the parameter list.Function and main program communicate by
parametersOrder the order of the parameters must be the same as
in the functions
Worked out Display statement
Supposs we do not want to store the answer in sum but we want to display the sum of the two numbers,the calling statement would be :
Display”the sum is”,calcSum(number1,number2)
Worked out wxampleif statement
The function can be called and the sum is used in the if statement
If calcSum(number1,number2) > 40 then
Display “the sum is greater than 40”
endif
A complete pseudocode using a functionThe program displays the total age for two friends
~get the user’s age and the user’s best friend ageSumOfTwoAges
Display”enter your age”
Input firstAge
Display”enter your friend’s age”
Input secondAge
~get the sum of both
total = sum (firstAge , secondAge )
~display the sum
Display” Together you are “total “years old”
End
~the sum function accepts two integer arguments and returns the sum of those arguments
Function sum(num1,num2)
Result= num1 + num2
Return result
End Function
What is happenning in the above programIn the main program the program gets two values from the user and stores these in the firstAge and secondAge variables. The statement :total = sum (firstAge , secondAge )
calls the sum function passing firstAge and secondAge as arguments.The value that is returned from the sum function is assigned to total variable .
NB:A function parameter list can be empty see following example
An empty parameter listWrite a program that computes the sale price fpr an item in a retail business.
To do that you will need to get the regular price of the item from the user.The function to do that would be:
Function getRegularPrice()
~get regular price
Display”enter the item’s regular price”
Input price
~return the regular price
Return price
End Function
In the main program to call that function :~get the item’s regular price
regularPrice = getRegularPrice()
Program with two functionThe program calcu;ates the sale price for an itemconstant DISCOUNT_PERCENTAGE
~The main program is the starting point of the program
SalePrice
~get item’s regular price
regularPrice = getRegularPrice()
~calculate sale price
salePrice=regularPrice-discount (regularPrice)
~Display Sale price
Display “The sale price is “ salePrice
End
~The getRegularPrice fmction prompts user to enter regular price of item and returns the price
Function getRegularPrice()
~get the regular price
Display ” Enter the item’s regular price
Input price
Return price
End
~The discount function accepts an item’s price as an argument and returns the amount of discount Function discount(price)
Return price * DISCOUNT_PERCENTAGE
End Function
About Functions The function name used in the calling statement and the function name
in the function header must always be the same. The names of the arguments and parameters need not be the same. The order of the variables in a calling statement’s argument list and the
parameters in the function header must always be the same. The number of variables in a calling statement’s argument list and the
number of parameters in the function header must always be the same. The name of the value returned by the function need not be the same as
in the calling statement. The arguments are only the names of the applicable variables in the
calling module. On the other hand, the parameters in the header must
indicate whether the parameter is a value parameter or a reference parameter – in other words, whether a copy or an address has been sent
Parameter A parameter is data (variables or values)
that is sent to a function, which it (function) needs to perform the task it has to do
Two types of parameters value parameters
– only a copy of the argument’s value is passed to the parameter variable
– If the contents of the parameter variable change it has no effect on the argument on the calling program
reference parameters.– Allows the module to change/modify the argument in the calling
part of the program
Variable scope is the part of the program in which the variable may be accessed
Argument ,ParameterArgument
any piece of data that is passed to the function when that function is called
Parameter
a variable that receives an argument that is passed into the function
Example 1(Functions)Reginald went to a shop to buy a number of fruit bars. The number bought
and the price of a fruit bar are entered in a main procedure. These numbers
need to be sent to a function to calculate the amount due. The amount due
must include 14% VAT. The calculated value must be returned to the main
procedure and displayed on the screen
PLANNING
Input and Output for the function and the main program
Description Type Variable nameMain procedure (ShoppingProgram)Input Number of items Integer numItems Price of one item Real priceOutput Amount due Real amtDueFunction (CalcAmtDue)Input Copy of number of items Integer valNum
Copy of price of one item Real valPrice
Output Amount due Real -not used-
Algorithm for Example 1Function CalcAmtDue (valNum, valPrice)
return (valNum * valPrice * 1.14)
ShoppingProgram
~ The input data will be entered in the main procedure.
~ The main procedure will call a function to calculate the amount due.
~ The amount due will be displayed in the main procedure.
display “Enter the number of fruit bars bought”
enter numItems
display “Enter the price of a fruit bar”
enter price
amtDue = CalcAmtDue (numItems, price) ~ Function call
display “The amount due is R”, amtDue
end
Example 2 functionsWrite an algorithm to enter three test marks for a student. A function is called to calculate the average mark. Another function is used to indicate whether the average mark is a pass mark (>=50) or a fail mark. The average as well as the result must be displayed on the screen. All input and output must be done in the main procedurePlanning
Description Type Variable name
Main procedure (ShowResults)
Input Student name String studentName
Test mark 1 Integer testMark1
Test mark 2 Integer testMark2
Test mark 3 Integer testMark3
Output Average mark Real average
Result String -not used-
Function (CalcAve)
Input Copy of test mark1 Integer valTest1
Copy of test mark2 Integer valTest2
Copy of test mark3 Integer valTest3
Output Average mark Real -not used-
Function (DetermineResults)
Input Copy of averagemark integer valAve
Output Result message String message
Algorithm for example2Function CalcAve (valTest1, valTest2, valTest3) ~ Function
~ Calculate and return the average of the three tests
return (valTest1 + valTest2 + valTest3) / 3
Function DetermineResults (valAve) ~ Function
~ Produce a message to express the outcome
message = “pass”
if valAve < 50 then
message = “fail”
endif
return message
ShowResults ~ Main procedure
~ This program determines the result of the student’s performance
display “Enter the student name”
enter studentName
display “Enter the first test mark”
enter testMark1
display “Enter the second test mark”
enter testMark2
display “Enter the third test mark”
enter testMark3
~ Call the function to calculate the average
average = CalcAve (testMark1, testMark2, testMark3)
display “The average mark for ”, studentName , “ is ”, average
~ Call the function to determine the result
display “This student will ”, DetermineResults(average)
end
Example3Identify and correct all the errors in the following function call and its
corresponding function header.
decPay = CalcPay(Hours, Tariff )
Function Pay(refTariff, valHours)
Answer
1.The function name should be the same in the function and in the statement calling the function i.e CalcPay should be Pay
2.The order of the parameters should be the same in the function and in the calling ststement i.e decPay = CalcPay(Tarrif, Hours )
Function Pay(refTariff, valHours)
Example 4Determine the output of each of the following algorithms:
Function Calculation(valX, valY)
return (valX + valY \ 2)
JustACalculation
a = 14
b = 5
answer = Calculation(a, b)
display “The answer is ”, answer
End
Answer
Output
The answer is 9
Example 5What is the output ?
Function AddNumbers(valA, valB)
c= valA + valB
return c
MainAlgorithm
a = 0
b = 1
do while a < 5
x = AddNumbers(a, b)
b = a + 5
a = a + 1
display “a = ”, a , “ b = ”, b , “ x = ”, x ~ Display on a new line
loop
End
Answer
OUTPUT
a = 1,b = 5, X = 1
a = 2, b = 6, X = 6
a = 3, b = 7 , X = 8
a = 4 , b = 8 , X = 10
TRY THE FOLLOWING ON YOUR OWN!1. Study each of the following function calls, then write the complete
function to calculate and return the answer.
1.1 BestMark = DetermineBest(Test1, Test2, Test3)
The function must determine and return the best of the three test
marks.
1.2 Average = CalcAverage(Test1,Test2, Test3)
The function must calculate and return the average of the three test
marks.
1.3Pay = CalcPay(Hours, Tariff )
The function must calculate the person’s pay by multiplying the hours
by the tariff per hour. If there are more than 40 hours, the person
receives 1½ times the tariff for all hours over 40.
1.4 NetMonthSal = CalcSal(GrossAnnSal, TaxPercentage)
The function must calculate and return an employee’s net monthly
salary from their annual gross salary as well as the percentage tax that
the person must pay. Deduct the tax amount from the monthly gross
salary to calculate the monthly net salary.
TRY THE FOLLOWING ON YOUR OWN!
Write a complete algorithm with functions to solve the following problem:
Enter the radius of a circle, then call one function to calculate the
circumference and another function to calculate the area of the circle.
Display the calculated values on the screen.
ALL THE BEST !!!
Subprocedures It can receive value parameters to use in the subprocedure It can receive reference parameters. It doesn’t return a value. It is able to manipulate data outside the subprocedure at specific addresses, as given in the reference parameters. In other words, it can change more than one value.
The subprocedure call syntax
call NameOfSubProcedure (argument list)
Example:
call Calculations(number1, number2, sum, product)
display “The sum of ”, number1, “ and ”, number2, “ = ”, sum
display “The product of ”, number1, “ and ”, number2, “ = ”, product
Calculations is the name of the subprocedure
number1 and number2 are value parameters they will not change
sum and product are two reference parameters values in these specific addresses may be changed
Subprocedure call
Subprocedures
call Calculations(number1, number2, sum, product)
The above is a subprocedure call.The actual subprocedure would be
Sub Calculations(valNo1, valNo2, refSum, refProduct)
~ Calculate the sum and the product of 2 numbers
refSum = valNo1 + valNo2
refProduct = valNo1 * valNo2
End Sub
NB: A function or subprocedure can be called from a main procedure or from
any other function or subprocedure as can be seen in some of the examples
Worked Example Subprocedure 1
Danny invested an amount at the Save-a-Lot Bank, which must be entered at
the beginning of the algorithm. The monthly interest rate is also entered. The
algorithm must calculate and display the amount of interest earned as well as
the balance at the end of every month for the next 15 months. At the end of
the algorithm the total amount of interest must be displayed. This example
uses functions and subprocedures where possible. A monthly interest rate is
used to test the program, for example an annual interest rate of 10% = 0.83%
per month.
Worked Example Subprocedure 1Algorithm
Sub DisplayResults (valMonth, valAmt, valMInt) ~ Display monthly values
display valMonth, “ ”, valAmt, “ ” , valMInt
End Sub
Sub CalcNewValues (valRate, refAmt, refMonthInterest)
refMonthInterest = refAmt * valRate / 100 ~ Calculate interest
refAmt = refAmt + refMonthInterest ~ increase amount
End Sub
Sub AccSum (valMInterest, refTInterest)
refTInterest = refTInterest + valMInterest ~ Accumulate interest total
End Sub
EarnInterest
~ This program deals with the investment of money
totInterest = 0
monInt = 0
~display Headings
display “Provide the amount you want to invest”
enter amount
display “Enter the monthly interest rate”
enter rate
call DisplayResults (0, amount, monInt) ~ Display initial values
~ Repeat 15 times to obtain final results
for x = 1 to 15
call CalcNewValues (rate, amount, monInt)
call DisplayResults (x, amount, monInt)
call AccSum (monInt, totInterest)
next x
display “The total amount of interest earned is R”, totInterest
end
Worked Example Subprocedure 2Write an algorithm to calculate the final marks students obtained for Programming 3. The final mark is calculated on the marks of various assessments and their particular weightings:
Assessment Weighting
Test 1 15%
Test 2 20%
The better of two classtest marks 15%
Examination 50%
HINT:
We’ll code a function to determine and return the higher mark of two class
tests. A subprocedure will be used to calculate the final mark and determine
whether it is a pass or fail (message), and another subprocedure will display the
mark and the message result.
AnswerFunction CalcClMark (valClMark1, valClMark2) ~ Function header
if valClMark1 > valClMark2
betterMark = valClMark1
else
betterMark = valClMark2
endif
return betterMark
Worked Example Subprocedure 2Sub CalcValues (valTest1, valTest2,valClassTest,valExam) ~ Subprocedure
final = valTest1 * 0.15 + valTest2 * 0.2 + valClassTest * 0.15 + valExam * 0.5
if final >= 50 then
message = “Pass”
else
message = “fail”
endif
call DisplayResults (final, message)
End Sub
Sub DisplayResults (valFinalMark, valMessage) ~ Subprocedure
display “The final mark of the student is “, valFinalMark
display “The result is “, valMessage
End Sub
CalcFinalMark
Main procedure
display “Provide the mark for test 1”
enter test1
display “Provide the mark for test 2”
enter test2
display “Provide the mark for class test 1”
enter clTest1
display “Provide the mark for class test 2”
enter clTest2
display “Provide the exam mark”
enter exam
betterClassTest = CalcClMark (clTest1, clTest2) ~ Function call
call CalcValues (test1, test2, betterClassTest, Exam) ~ Call subprocedure
end
As mentioned earlier, a function or subprocedure can be called from a
main procedure or from any other function or subprocedure.
Determine the outputSub IsntItLovely (valA, refB, valC, refD)
refD = valA
if refB mod 3 = 0 then
refB = refB + 2
endif
refD = valA + (valC mod 5)
valA = valA + 2
valC = valC + 1
End Sub
MainAlgorithm
w = 0
x = 3
y = 8
z = 6
for m = 4 to 9 step 3
w = m
call IsntItLovely(w,x,y,z)
display “w = ” , w , “ x = ” , x , “ y = ” , y , “z = ”, z
next m
end
Determine the outputSub CalcProc (valA, refB)
c = valA * 3
refB = c - refB
End Sub
Function CalcFunc (valK)
return ((valK * 2) mod 4)
MainModule
m = 4
l = 1
k = 2
do
j = CalcFunc (m)
call CalcProc (j, k)
display “ l = “ , l , “ j = “ , j , “k = “, k , “m = “, m
m = m + 1
loop until m > 5
end