COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02 Reading:...
-
Upload
nickolas-byrd -
Category
Documents
-
view
225 -
download
0
Transcript of COIT29222 Structured Programming 1 COIT29222-Structured Programming Lecture Week 02 Reading:...
COIT29222 Structured Programming 1
COIT29222-Structured Programming Lecture Week 02
Reading: Textbook(4th Ed.), Chapter 2 Textbook (6th Ed.), Chapters 4, 5 Study Guide Book 1, Module 4
Variables Branching or selection statementsLooping statements
Expressions, Operators, Operands, etc
COIT29222 Structured Programming 2
VariablesInstead of using memory locations directly, all
modern programming languages use names to refer to memory locations
We call these things variables – the values they refer to vary as the program runs
Using names, instead of memory locations, makes programs easier to read
Instead of…
COIT29222 Structured Programming 3
Example Pseudocodewrite “Number of marks in exam ==> “ read M1 write “Student’s mark ==> “read M2set M3 to M2 / M1set M4 to 100 * M3write “Student’s percentage: “write M4
COIT29222 Structured Programming 4
Variableswrite “Number of marks in exam ==> “ read NbrMarks write “Student’s mark ==> “read StudentMarkset ProportionOfMarks to StudentMark / NbrMarks set Percentage to 100 * ProportionOfMarkswrite “ Student’s percentage: “write Percentage
4 variables: NbrMarks, StudentMark, ProportionOfMarks,
Percentage
COIT29222 Structured Programming 5
Alternative Designwrite “Number of marks in exam ==> “ read NbrMarks write “Student’s mark ==> “read StudentMarkset Percentage to 100 * StudentMark / NbrMarkswrite “ Student’s percentage: “write Percentage
3 variables: NbrMarks, StudentMark,Percentage
In C++, this looks like…
COIT29222 Structured Programming 6
Sample Program In C++
#include <iostream.h>void main (void){ int NbrMarks = 0; float StudentMark = 0, Percentage = 0; cout << "Number of marks in exam ==> "; cin >> NbrMarks; cout << "Student’s mark ==> "; cin >> StudentMark; Percentage = 100 * StudentMark / NbrMarks; cout << " Student’s percentage: "; cout << Percentage;
}
COIT29222 Structured Programming 7
Declaring VariablesIn C++, you must declare variables before you
use them
Also, you must declare the type of value each variable will hold
The first variable declared is NbrMarks – it can hold any integer value
int NbrMarks = 0;
An integer is any +ve or –ve whole number, or zero: …-3, -2, -1, 0, 1, 2, 3, …
COIT29222 Structured Programming 8
Naming Variables Start with a letter - A to Z
Can contain upper or lower case letters, or numerals - 0 to 9
Good idea to limit names to 32 characters
Must avoid C++ reserved words like int, float, void, etc
More later…
COIT29222 Structured Programming 9
Initialising VariablesOur declaration of NbrMarks also gives it an
initial value - 0
int NbrMarks = 0;
If you do not give a variable an initial value, it will hold whatever data was left in memory by the previous program
Incorrect initialisation of variables is a very common logic error made by programmers
Please read the previous point again!
COIT29222 Structured Programming 10
More DeclarationsOur program also declares two floating point
variables – StudentMark and Percentage
float StudentMark = 0, Percentage = 0;
We use variables of type float to hold values that may not be an integer
Examples:
An student’s mark: 15.5 (marks)
A distance: 123.456 (meters)
A temperature: -2.3 (degrees C)
COIT29222 Structured Programming 11
Why “Floating Point”Some programs need to store very big numbers
– eg. 1,234,500,000,000,000,000; others need to store very small numbers - 0.000000000012345
These two numbers can be represented as:1.2345 * 1018 and 1.2345 * 10-12
float variables are stored in two parts:number part : 1.2345 in above casespower part : 18 or –12 in above cases
Decimal point “floats around”, depending on power part – more details later
COIT29222 Structured Programming 12
More On DeclarationsWe could declare these variables like this:
float StudentMark = 0; float Percentage = 0;
Instead, a comma was used to separate two variables of the same type
float StudentMark = 0, Percentage = 0;Breaking the declaration over two lines is
optional in C++ - it’s “common practice”
float StudentMark = 0, Percentage = 0;
Notice how a comma is used here to separate two use of punctuation - , and ;
COIT29222 Structured Programming 13
BranchingOur example program always performs the exact
same actions: get number of marks in exam get student’s mark calculate the student’s percentage display the student’s percentage
In practice, most programs are capable of performing different actions, depending on the inputs provided by the user
e.g., we may want to also state if the student passed the exam – so, sometimes the program will need to output “Pass”, otherwise “Fail”
COIT29222 Structured Programming 14
Sample Dialogs
Number of marks in exam ==> 80
Student’s mark ==> 60
Student’s percentage: 75 (Pass)
or…
Number of marks in exam ==> 80
Student’s mark ==> 20
Student’s percentage: 25 (Fail)
COIT29222 Structured Programming 15
Branching StatementsTo enable programs to perform different actions
(depending on user input) all programming languages include one or more branching or selection statements
The branching statement selects between one of more possible paths through the program
All programming languages include some form of if-then-else statement
COIT29222 Structured Programming 16
Pseudocode Examplewrite “Number of marks in exam ==> “ read NbrMarks write “Student’s mark ==> “read StudentMarkset Percentage to 100 * StudentMark / NbrMarkswrite “ Student’s percentage: “write Percentageif Percentage < 50 then write “ (Fail)”else write “ (Pass)”
COIT29222 Structured Programming 17
Example of if-then-elsewrite “Number of marks in exam ==> “ read NbrMarks write “Student’s mark ==> “read StudentMarkset Percentage to 100 * StudentMark / NbrMarkswrite “ Student’s percentage: “write Percentageif Percentage < 50 then write “ (Fail)” NbrMarks: ?else StudentMark: ? write “ (Pass)” Percentage: ?in C++, this looks like…
COIT29222 Structured Programming 18
if-else Statements
#include <iostream.h>void main (void){ float StudentMark = 0; cout << "Student’s mark ==> "; cin >> StudentMark; if (StudentMark >= 50) {
cout << "Pass!"; } else {
cout << "Fail!"; }
}
COIT29222 Structured Programming 19
if-else StatementsNotice that comparison between StudentMark
and 50 is enclosed in parentheses
if (StudentMark >= 50)
Also, braces mark start and end of the if-branch (shown below), and the else-branch {
cout << "Pass!"; }
Indentation makes code easier to read – it’s not required by the compiler
COIT29222 Structured Programming 20
if-else-if Statements if-else-if statements can be coded as: if (StudentMark >= 75) {
cout << “Distinction!"; } else if (StudentMark >= 50) {
cout << “Pass!"; } else {
cout << "Fail!"; }
COIT29222 Structured Programming 21
Activity – Code in C++write “Select conversion - (1) C to F, (2) F to C
==> “read ConversionTypewrite “Input temperature ==> “read Temperaturewrite “Converts to ”if ConversionType = 1 then write 32 + (Temperature * 1.8) write “ degrees Fahrenheit”else write (Temperature – 32) / 1.8 write “ degrees Centigrade”
COIT29222 Structured Programming 22
A Start#include <iostream.h>void main (void){ int ConversionType = 0; float Temperature = 0; cout << "Select conversion - (1) C to F, (2) F to C ==> "; cin >> ConversionType;
}
COIT29222 Structured Programming 23
A Solution#include <iostream.h>void main (void){ int ConversionType = 0; float Temperature = 0; cout << "Select conversion - (1) C to F, (2) F to C ==> "; cin >> ConversionType; cout << "Input temperature ==> "; cin >> Temperature; if (ConversionType == 1) {
cout << 32 + (Temperature * 1.8); cout << " degrees Fahrenheit";
} else { cout << (Temperature - 32) / 1.8; cout << " degrees Centigrade"; }}
note: C++ uses == instead of = for testing equality
COIT29222 Structured Programming 24
LoopingOur program to calculate the exam
percentage for a single student performs the following 5 tasks: get number of marks in exam get student’s mark calculate the student’s percentage display the student’s percentage display “Pass” or “Fail”
To calculate the exam percentage for more than one student, a program must perform some of these tasks more than once…
COIT29222 Structured Programming 25
LoopingTo calculate the percentage for 2 students, a
program must perform 9 tasks: get number of marks in exam get student’s mark calculate the student’s percentage display the student’s percentage display “Pass” or “Fail” get student’s mark calculate the student’s percentage display the student’s percentage display “Pass” or “Fail”
COIT29222 Structured Programming 26
LoopingTo calculate the percentage for 3 students, a
program must perform 13 tasks: get number of marks in exam get student’s mark calculate the student’s percentage display the student’s percentage display “Pass” or “Fail” get student’s mark calculate the student’s percentage display the student’s percentage display “Pass” or “Fail” get student’s mark calculate the student’s percentage display the student’s percentage display “Pass” or “Fail”
COIT29222 Structured Programming 27
LoopingWe could have:
-One program to handle 2 students, -Another program to handle 3 students, etc
It would be better to have a single program to handle any number of students
We would like to design a program to repeat some actions more than once
We want our program to: get the number of marks in exam from user- repeat as required - get student’s mark calculate the student’s percentage display the student’s percentage display “Pass” or “Fail”
COIT29222 Structured Programming 28
LoopingOne design is…
Ask user for number of students at start: get number of marks in exam get number of students- repeat once for each student - get student’s mark calculate the student’s percentage display the student’s percentage display “Pass” or “Fail”
Another design is…
COIT29222 Structured Programming 29
LoopingKeep asking if the user has more students:
get number of marks in exam- repeat while user wants more students - get student’s mark calculate the student’s percentage display the student’s percentage display “Pass” or “Fail” ask user if they have more students
COIT29222 Structured Programming 30
Looping StatementsTo enable programs to perform different numbers
of actions (depending on data inputs) all programming languages include one or more looping or repetition statements
All programming languages include some form of while statement...
Other common looping statements are do-while and for
COIT29222 Structured Programming 31
Pseudocode Examplewrite “Number of marks in exam ==> “ read NbrMarks write “Number of students ==> “ read NbrStudents set NbrProcessed to 0while NbrProcessed < NbrStudents write “Student’s mark ==> “ read StudentMark set Percentage to 100 * StudentMark / NbrMarks write “ Student’s percentage: “ write Percentage set NbrProcessed to NbrProcessed + 1
COIT29222 Structured Programming 32
Example of whilewrite “Number of marks in exam ==> “
NbrMarks:
80read NbrMarks
NbrStudents:
2write “Number of students ==> “
NbrProcessed:
2read NbrStudents
StudentMark:
40set NbrProcessed to 0
Percentage:
50while NbrProcessed < NbrStudents write “Student’s mark ==> “ read StudentMark set Percentage to 100 * StudentMark / NbrMarks write “ Student’s percentage: “ write Percentage set NbrProcessed to NbrProcessed + 1
COIT29222 Structured Programming 33
ActivityShow the output produced by the following pseudocode.
set TotalCost to 20set ItemCost to 5set NumberOfItems to 0while TotalCost > 0 set TotalCost to TotalCost - ItemCost set NumberOfItems to NumberOfItems + 1write “Number of items purchased: “write NumberOfItems
COIT29222 Structured Programming 34
while Statement
#include <iostream.h>void main (void){ int NbrTimesTold = 0,
NbrTimesToTell = 0; cout << "How many times must I tell you? ==> "; cin >> NbrTimesToTell;
while (NbrTimesTold < NbrTimesToTell) {
cout << “ No new taxes!"; cout << endl; NbrTimesTold = NbrTimesTold + 1;
}}
COIT29222 Structured Programming 35
Activity FeedbackThe program displays “No new taxes!”
the number of times requested by the user…
cout << endl; moves to start of next line
How many times must I tell you? ==> 3 No new taxes! No new taxes! No new taxes!
COIT29222 Structured Programming 36
while StatementThings to notice:
Comparison enclosed in parentheses
while (NbrTimesTold < NbrTimesToTell) {
cout << endl; cout << " No new taxes!"; NbrTimesTold = NbrTimesTold + 1;
}
Use of braces and indentation
COIT29222 Structured Programming 37
One More Detail About C++All compilers are fussy about punctuation
C++ compilers are also fussy about case
The following code has 3 compilation errors…
#Include <iostream.h> void Main (void) {
Cout << "Hello World!"; }
COIT29222 Structured Programming 38
C++ is Case-Sensitive
#Include <iostream.h> void Main (void) {
Cout << "Hello World!"; }
This program has three errors:it should be #include , not #Includeit should be main , not Mainit should be cout , not Cout
C++ compilers are case-sensitive
COIT29222 Structured Programming 39
Data ProcessingWe said that computers are data processing
devices – they convert input data into output data
Where does all the data processing occur in a program?
Recall our sample program...
COIT29222 Structured Programming 40
Sample Programwrite “Number of marks: “ read NbrMarks write “Student’s mark: “read StudentMarkset ProportionOfMarks to StudentMark / NbrMarks set PercentageOfMarks to ProportionOfMarks *
100write “ Student’s percentage: “write PercentageOfMarks
In this program, all the data processing occurs in assignment statements
COIT29222 Structured Programming 41
Anatomy of an AssignmentLet’s analyse the assignment statement…
Here, the two assignment statements are: set ProportionOfMarks to StudentMark / NbrMarks set PercentageOfMarks to ProportionOfMarks * 100
That is: set < variable > to < value of interest >
Here, the values of interest are: StudentMark / NbrMarks ProportionOfMarks * 100
COIT29222 Structured Programming 42
ExpressionsWe use the term expression to mean:
the description of a value of interest
we describe the value that we wish to assign to a data object in an expression
so: StudentMark / NbrMarks ProportionOfMarks * 100
are two expressions
COIT29222 Structured Programming 43
Data Processing
So, where does the data processing happen?
answer: some of it happens in
assignment statements
It can also happen in output statements…
COIT29222 Structured Programming 44
Alternative Design
write “Number of marks: “ read NbrMarks write “Student’s mark: “read StudentMarkset ProportionOfMarks to StudentMark / NbrMarks write “ Percentage: “write ProportionOfMarks * 100
COIT29222 Structured Programming 45
Anatomy of an OutputThe anatomy of our assignment statement is: set < variable > to < expression >
the anatomy of our output statement is: write < expression >
so, where does all the data processing happen?
Expressions !
COIT29222 Structured Programming 46
ExpressionsClearly, expressions are important - that’s
where the data processing happens
Let’s take a closer look at expressions
Previously, we said that data was numbers and text -for now, we just deal with expressions to process numbers
The anatomy of an expression is one we’ve seen before...
COIT29222 Structured Programming 47
Expressions as a Black BoxWe can think of an expression as a black
boxExpressions have one or more input values
and produce one output value - the input-process-output model again
Example: StudentMark / NbrMarks
input process output
StudentMark ? NbrMarks (a single value - depends on inputs)
COIT29222 Structured Programming 48
Operatorswe use the term operator to mean:
a symbol, or name, used to represent an operation that can be performed on data
in the two expressions: StudentMark / NbrMarks ProportionOfMarks * 100
the operators are:/ for division* for multiplication
+ and - are used for addition and subtraction+, -, *, / all work in C++ as you would expect
COIT29222 Structured Programming 49
OperandsWe use the term operand to mean:
an input to an expressionIn the two expressions: StudentMark / NbrMarks ProportionOfMarks * 100
The operands are:StudentMark and NbrMarks
ProportionOfMarks and 100
COIT29222 Structured Programming 50
Binary OperatorsIn the following examples: StudentMark / NbrMarks ProportionOfMarks * 100 NbrMarks - StudentMark StudentMark + 10
Each operator is used with two operands
So / , * , - and + are binary operators –they can all be used with two operands
COIT29222 Structured Programming 51
Unary OperatorsThe + and - operators are also unary
operators (they can be used with just one operand)
Examples: -273.15 as in set AbsoluteZero to -273.15 +100 as in set BoilingPointOfWater to
+100 expression - 273.15
operandoperator
COIT29222 Structured Programming 52
Numeric Expressions expressions that evaluate to a number are
called numeric expressions numeric expression come in all shapes and
sizes: a number by itself – a literal: set NbrTimesTold to 0 the name of a variable: write Percentage expressions that use operators: set NbrTimesTold to NbrTimesTold + 1
COIT29222 Structured Programming 53
Power of Expressions The arithmetic operators +, -, * and / give us a
powerful language to process numbersThe power comes from the ability to nest little
expressions inside bigger expressionsInstead of:set ProportionOfMarks to StudentMark / NbrMarks write ProportionOfMarks * 100We can write:write StudentMark / NbrMarks * 100
question: which operator is applied first here? and, does it matter?
COIT29222 Structured Programming 54
Nested Expressionswhich operator is applied first here?
Is the division first?
StudentMark / NbrMarks * 100
divide StudentMark by NbrMarks, then multiply by 100
Or is the multiplication first?
StudentMark / NbrMarks * 100
multiply NbrMarks by 100, then divide StudentMark by result of multiplication
Activity: does it matter?
COIT29222 Structured Programming 55
Activity FeedbackUsing StudentMark = 50, NbrMarks = 100…
Division first: (StudentMark / NbrMarks) * 100= (50 / 100) * 100= 50
Multiplication first:StudentMark / (NbrMarks * 100)= 50 / (100 * 100)= 0.005
Will a C++ program do it in the correct order?
COIT29222 Structured Programming 56
Order of Use There are rules to decide the order in which
operators in an expression are appliedUnary operators before binary operatorsMultiplication (*) and division (/) before
addition (+) and subtraction (-)Otherwise, left to right
Evaluate the following: 4 * -2 + 3 2 + 12 / 4 * 3
Will the following be evaluated correctly?StudentMark / NbrMarks * 100
COIT29222 Structured Programming 57
Activity Feedback Evaluate:
4 * -2 + 3unary operator first (- applies to 2)multiplication before addition (4 * -2) + 3= -8 + 3= -5
COIT29222 Structured Programming 58
Activity FeedbackEvaluate the following:
2 + 12 / 4 * 3Multiplication and division before additionLeft to right otherwise – so division before
multiplication here2 + (12 / 4) * 3
= 2 + 3 * 3Multiplication before addition= 2 + (3 * 3)= 2 + 9= 11
COIT29222 Structured Programming 59
Activity FeedbackWill the following be evaluated correctly?
StudentMark / NbrMarks * 100
Yes it will – since the division occurs before the multiplication, this is the same as:
(StudentMark / NbrMarks) * 100
COIT29222 Structured Programming 60
Order of Use Avoid errors by using parentheses:
(4 * -2) + 3 2 + ( ( 12 / 4 ) * 3 )
Sometimes you can rewrite an expression to make it easier to read – instead of:StudentMark / NbrMarks * 100
You can write:100 * StudentMark / NbrMarks
Is this easier to understand? if so, why?
COIT29222 Structured Programming 61
Activity FeedbackThe expression:
100 * StudentMark / NbrMarks
may seem easier to read than:StudentMark / NbrMarks * 100
Possibly because, in the first expression above, the order in which operators are applied doesn’t matter
– left for student to checkAlways keep you code as simple as possible
The following program is designed to convert temperatures between Fahrenheit and Centigrade
It has a logic error – fix it…
COIT29222 Structured Programming 62
#include <iostream.h>void main (void){ int ConversionType = 0; float Temperature = 0; cout << "Select conversion - (1) C to F, (2) F to C ==> "; cin >> ConversionType; cout << "Input temperature ==> "; cin >> Temperature; if (ConversionType == 1) {
cout << 32 + Temperature * 1.8; cout << " degrees Fahrenheit";
} else { cout << Temperature - 32 / 1.8; cout << " degrees Centigrade"; }}
COIT29222 Structured Programming 63
#include <iostream.h>void main (void){ int ConversionType = 0; float Temperature = 0; cout << "Select conversion - (1) C to F, (2) F to C ==> "; cin >> ConversionType; cout << "Input temperature ==> "; cin >> Temperature; if (ConversionType == 1) {
cout << 32 + Temperature * 1.8; cout << " degrees Fahrenheit";
} else { cout << Temperature - 32 / 1.8; cout << " degrees Centigrade"; }}
problem here: division occurs before subtraction
Feedback
COIT29222 Structured Programming 64
#include <iostream.h>void main (void){ int ConversionType = 0; float Temperature = 0; cout << "Select conversion - (1) C to F, (2) F to C ==> "; cin >> ConversionType; cout << "Input temperature ==> "; cin >> Temperature; if (ConversionType == 1) {
cout << 32 + (Temperature * 1.8); cout << " degrees Fahrenheit";
} else { cout << (Temperature – 32) / 1.8; cout << " degrees Centigrade"; }}
a solution: enclose subtractionin parentheses
clarification: parentheses make intention clear
Feedback
COIT29222 Structured Programming 65
C++ Syntax Summaryinput : cin >> <variable>; output : cout << <expression>;assignment : <variable> = <expression>;
A selection statement: if ( <test> ) { <if-block statements> } else { <else-block statements> }
A repetition statement: while ( <test> ) { <while-block statements> }
COIT29222 Structured Programming 66
SummaryFive base programming statements are: input,
output, assignment, selection, repetition
These statements provide a platform for programming in all popular languages
Data processing happens in expressions
Different types of expressions – literals, variables names, ones that use operators…
Arithmetic operators are: +, -, *, /
Rules control order of application
Parentheses are used to impose ordering