Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 144

Principles of

Computer
1
Programming
LECTURE NOTES

Dr George O. Ofori-Dwumfuo
BSc, PhD, FBCS, JP
Wisconsin Int Univ College

Mar 27, 202


4
Syllabus
2
 Data Type Declaration; integers, reals, characters
 Variables (name versus values)
 Input-output
 Assignment statements
 Arithmetic and logical expressions
 Program logic;
 sequencing and flowcharting
 Iterations and loops
 Arrays
 Subroutines and recursion
 Program errors; syntax, run-time
Mar 27, 202
4
3 Course Project
 A project scenario will be used during this course.
 The scenario will be developed weekly
 Program constructs will be developed and written weekly (in C++)
 Ultimately, by the end of the course, students would be able to
develop at least one program based upon the project scenario
 The program to be developed will be a concatenation of the various
program constructs developed over the weeks.
 All course participants must therefore bring an exercise book (not
scrap paper) and a pen

Mar 27, 202


4
Course Project…
4 Wesleyan University Student Results Processing
 Wesleyan University (WU) is a renowned academic institution with
over 35,000 students on three campuses; Dansoman, Tema and Wenchi.
The average class size is about 60 students for various courses.
 You are a programming guru, and you have been tasked by WU to
develop a program for them to process student results at the end of each
academic semester.
 Processing involves:
 Keeping track of each student from each campus
 Each course shall be graded over 100%; broken down into two segments, Continuous Assessment and Final
Examination, in the ratio of 30:70
 Continuous Assessment marks may be further broken down depending upon the number of assignments
given and the semester Intermediate Assessment examination.
 The Final Examination marks may also be further broken down depending upon the number of questions
given in the examination.
 Further details of the program development shall be given as the course
progresses
Mar 27, 202
4
HIGH LEVEL LANGUAGE PROGRAMS
5
Introduction
 Programming is a core activity in the process of performing
tasks or solving problems with the aid of a computer. An
idealised picture is:
 [problem or task specification] - COMPUTER - [solution or completed task]
 Unfortunately, the "specification" cannot be given to the
computer using natural language.
 Moreover, it cannot (yet) just be a description of the problem or
task, but has to contain information about how the problem is
to be solved or the task is to be executed.
 Hence we need programming languages.
 Thus, problems have to be stated as programs in programming
languages if they are to be implemented by a computer.
Mar 27, 202
4
6 Introduction…
 English language or conventional languages are not used
because of ambiguity, eg.
 The statement:
TIME FLIES LIKE AN ARROW
may be understood in different ways depending upon who
reads it.
 There are many different programming languages, and
many ways to classify them.

Mar 27, 202


4
7 Introduction…

 "high-level" programming languages


are languages whose syntax is
relatively close to natural language,
 whereas the syntax of "low-level"
languages includes many technical
references to the 0's and 1's, etc. of the
computer.

Mar 27, 202


4
8 Introduction…
 Declarative" languages (as opposed to "imperative" or "procedural"
languages) enable the programmer to minimise his or her account of
how the computer is to solve a problem or produce a particular
output.
 "Object-oriented languages" reflect a particular way of thinking
about problems and tasks in terms of identifying and describing the
behaviour of the relevant "objects".
 Smalltalk is an example of a pure object-oriented language.
 C++ includes facilities for object-oriented programming, as well as
for more conventional procedural programming.

Mar 27, 202


4
9 Introduction…
 The programming language used will be understood by the
computer if the corresponding translator, or compiler, is available in
its memory.
 The compiler will make the final translation into the machine’s own
internal language.
 Programs are therefore sequences of statements that can be
understood by a computer.
 There are several kinds of statements each designed to perform its
own part of the processing operation.
 Examples in this course will be based upon the C++ programming
language.

Mar 27, 202


4
10 Programming Environment
 The best way to learn a programming language is to try writing
programs and test them on a computer! To do this, we need several
pieces of software, etc.:
 A pen and paper with which to write the program,
 An editor with which to type and modify the (C++) program
components or source code,
 A compiler with which to convert the source code into machine
instructions which can be executed by the computer directly,
 A linking program with which to link the compiled program components
with each other and with a selection of routines from existing libraries
of computer code, in order to form the complete machine-executable
object program,
 A debugger to help diagnose problems, either in compiling programs in
the first place, or if the object program runs but gives unintended results.
Mar 27, 202
4
11
High-level Language Character
Set
All high-level language programs are written using more or less
the same alphabets and the same set of numerical and
graphical characters;

 Numeric characters 0 1 2 …..
 Alphabetic characters A B C ….Z a b c ….z
 Special characters + - * / ( ) = , . $ % & ; : etc.
 The blank, or space (sometimes this can be inserted freely in a
stream of information without altering the meaning of other
characters, but at times its presence counts).
Mar 27, 202
4
12 Program Comments
 Program Comments (or Remarks) are used to document or
describe a program, making its purpose and flow clearer.
 They initiate no processing.
 Putting comments in programs is a service to others who may
have to read the program, and even to its author should that
individual return to the program after a period of disuse.
 Documentation is particularly important for large programs
prepared by teams, where team members write sections and
combine results, checking each other’s work.
 Using comments is good practice for any program.

Mar 27, 202


4
Example Comments (C++)
13

 // The C++ compiler ignores comments which start with


 // double slashes like this, up to the end of the line.

 /* Comments can also be written starting with a slash followed by a star, and
ending with a star followed by a slash. As you can see, comments written in this
way can span more than one line. */

 /* Comments help in program documentation. Documentation is important; it
makes programs understandable */

 /* Programs should ALWAYS include plenty of comments! */

 /* Comments could include the author of the program, date written, date last
Mar 27, 202
modified, overall purpose of the program, etc. */ 4
14 Variables and Identifiers
 Variables provide a means of associating a
storage location with a name or identifier.

 i.e it represents a space in a computer’s


memory that is assigned to store a value.

 The name of the variable is then used in code to


reference the value that is stored in that memory
space

 Identifiers are simply symbolic names used in computer


programming to refer to the value that the variable
contains.

 The two terms are often used interchangeably


Mar 27, 202
4
15 Variables and Identifiers (cont)

 Data can be stored in variables, which


are named containers for data values.

 Using variables involve a two-step process:


 First, you must declare the variable.
 Second, you must assign a value to it.

 Whenever you declare a variable, you are


creating a space in memory that can hold
a value of a certain data type.
Mar 27, 202
4
16 Identifiers
 Thus, an identifier is a name given to some program element.
Identifiers (variables or names) are needed for all
variables in a program.
 They must usually begin with a letter, which may then be
followed by a mix of letters, underscore and numerals.
Examples:
 firstname, smallest, locate_minimum, final_rslt, capital_o2,
year_now, result, another_age.

Mar 27, 202


4
17 Identifiers…

 An identifier cannot just be any sequence


of symbols.
 A valid identifier must start with a letter
of the alphabet and
 must consist only of letters, digits, and
underscores; no spaces!!

Mar 27, 202


4
18 Identifiers…
 It is useful to think of words found in a program as being one of
three types:

 Reserved Words. These are words such as if, int and else, which
have a predefined meaning that cannot be changed. These words
cannot be used as identifiers, since they play key roles in the
language.
 Library Identifiers. These words are supplied default meanings by
the programming environment, and should only have their
meanings changed if the programmer has strong reasons for doing
so. Examples are cin, cout and sqrt (square root).
 Programmer-supplied Identifiers. These words are "created" by the
programmer, and are typically variable names, such as firstname,
Mar 27, 202
year_now, capital_o2 and another_age. 4
19 Identifiers…
 Identifiers have two aspects: name and value.
 The name of an identifier remains the same all
through the program, but
 its value may change from time to time
depending upon the processing going on.

This is a box called CHOP_BOX

Its name shall remain so but its contents


can change from semester to semester.

This semester – garri.

Ie, CHOP_BOX <- garri

Next semester – corn_flakes

& CHOP_BOX <- corn_flakes


Mar 27, 202
4
20 Purpose of a variable/identifier

 Purpose of a variable:
 simply put, is to save some value off, until
you are ready to:
 use it,
 refer it,
 compare it with something else,
 or evaluate it against something else.

Mar 27, 202


4
Course Project…
21
WU Student Results Program

 (Stage 1)
 Write comments suitable for the WU Student
Results Program (WUSRP)

 (Stage 2)
 List possible identifiers suitable for the WU
Student Results Program (WUSRP)

Mar 27, 202


4
22 Data Types
 Data are usually of various types.
 For example:
 the numbers 2, 45 and 429 are of type integer;
 2.5, 5.3612, 4.352 are of type decimal / floating point;
 oranges, pineapples and bananas are of type fruits
 lizards, alligators, chameleons are of type ????
 Programming languages, including C++, require that
all variables used in a program be given a data type.

Mar 27, 202


4
23 Integers
 One data type is integer (represented int in C+
+).
 Variables of this type are used to represent
integers (whole numbers).
 Declaring a variable to be of type int (in C++)
signals to the compiler that it must associate
enough memory with the variable's identifier
to store an integer value or integer values as
the program executes.
 (But there is a system dependent limit on the
largest and smallest integers that can be
Mar 27, 202
stored!) 4
24 Integers…
 Some rules have to be observed:
 Decimal points cannot be used;
 although 26 and 26.0 have the same value, "26.0" is not of
type "int".
 Commas cannot be used in integers,
 So 23,897 has to be written as "23897".
 Integers cannot be written with leading zeros. The compiler
will, for example, interpret "011" as an octal (base 8) number,
with value 9.

Mar 27, 202


4
25 Real numbers
 Variables of type "float" are used to store real
numbers.
 Plus and minus signs for data of type "float" are
treated exactly as with integers, and
 trailing zeros to the right of the decimal point are
ignored.
 Hence "+523.5", "523.5" and "523.500" all represent
the same value.
 The computer also accepts real numbers in floating-
point form (or "scientific notation"). Hence 523.5
could be written as "5.235e+02" (i.e. 5.235 x 10 x
10), and -0.0034 as "-3.4e-03".
Mar 27, 202
4
26 Characters
 Variables of type "char" are used to store character data.
 In standard C++, for example, data of type "char" can only be
a single character (which could be a blank space).
 These characters come from an available character set which
can differ from computer to computer.
 However, it always includes upper and lower case letters of
the alphabet, the digits 0, ... , 9, and some special symbols
such as #, £, !, +, -, etc.

Mar 27, 202


4
27 Characters…
 Character constants of type "char" must be
enclosed in single quotation marks when used in
a program,
 otherwise they will be misinterpreted and may
cause a compilation error or unexpected program
behaviour.
 For example, 'A' is a character constant, but A
will be interpreted as a program variable.
 Similarly, '9' is a character, but 9 is an integer.

Mar 27, 202


4
28 Characters…
 Characters are actually represented as
integers inside the computer.
 Hence the data type "char" is simply a
subset of the data type "int".
 We can even do arithmetic and
comparisons with characters!

Mar 27, 202


4
29 Strings
 We usually use the type "string" in output.
 In C++, for example, a string constant must be enclosed in
double quotation marks.
 Hence, in programs, we shall see output statements such as:
cout << " pass mark for this course is forty ";

 In fact, "string" is not a fundamental data type such as "int",


"float" or "char".
 Instead, strings are represented as arrays of characters
(discussed again later).
Mar 27, 202
4
30 User Defined Data Types
 Later in programming, you will see how
the programmer may define his or her
own data types.
 This facility provides a powerful
programming tool when complex
structures of data need to be represented
and manipulated by a program.
Mar 27, 202
4
31 Data Type Declarations

 In most programming languages, variables have


to be declared before they can be used in a
program.
 A declaration statement causes the computer to
reserve a location in its memory for a variable
whose name is provided.
 Information about the nature or type of the
variable is also disclosed.

Mar 27, 202


4
32 Examples
The declaration:
a) int year_now, age_now, another_year, another_age; reserves
memory for representing four integers.
b) float number;

Between a declaration statement , eg, b) and the first statement which


assigns "number" an explicit value, the value contained in the
variable "number" is arbitrary.
 In many programming languages (including C++), it is possible and
desirable to initialise variables with a particular value at the same
time as declaring them.
 Hence we can write
double PI = 3.1415926535; Mar 27, 202
4
33 Constants
We can also specify that a variable's value cannot be
altered during the execution of a program (with the
reserved word "const“ in C++).

 Generally speaking, it is considered good practice


to put constant declarations before the "main"
program heading, and variable declarations
afterwards, in the body of "main".

Mar 27, 202


4
Input statements
34
 Values are often assigned to variables by reading them from
terminal, tape, disk or elsewhere.
 Input statements arrange for the transfer of information between the
source and the variable.
 Data must usually be supplied in the order called for.

 There are many forms of input statement.


 The simplest are called unformatted. (C++ uses cin)
 This asks only that the data be supplied in proper order;
 each value of a type consistent with the declared attributes of the
associated variable, and
 each separated from other values by a comma (or a blank space in
Mar 27, 202
some languages) . 4
35 Examples:
a) The program statement
 cin >> year_now;
will result in the variable year_now being
assigned the value 2001 (at the point when
the user presses RETURN after typing in
"2001“).
b) cin >> age_now;
c) cin >> another_year;

Mar 27, 202


4
36 Assignment Statements
 These are the main processing statements of most programs.
 The general form is:
“The value of a named variable is set to the computed value of a
given expression”, ie,

 <variable>  <value of expression>


In brief, the variable is assigned the value of that expression.

 In most languages if the variable named has not been included


in a declaration statement, then a memory location will
automatically be reserved for it when assignment is first made.
It is, however, good practice to declare all variables for Mar 27, 202
4
documentation.
37 Assignment Statements:
Arithmetic
 In arithmetical operations, the four familiar operations will
be represented by + for addition, - for subtraction, * for
multiplication and / for division, while ** or up arrow ↑
usually stands for exponentiation.
 The operations are performed according to the usual
mathematical priorities.
 Parenthesis are used to frame parts of an expression when
other priorities are needed.

Mar 27, 202


4
38 Examples:
a) another_age = another_year - (year_now - age_now);
The symbol = means "is assigned the value of". ("Equals" is represented in C++
as ==.)

b) number = number + 1;

 In each example above, the expression on the right is computed, and the resulting
value assigned to the variable named on the left

 In the second example above, the current value of the variable number is used in
evaluating the expression on the right hand side.
 The result is then assigned to the same memory location, that of number.
 Thus number on the right refers to the old number, while the same name on Mar
the27,left
202
4
refers to the new.
Assignment Statements: Logical
39

 We often think of expressions such as "2 < 7", "1.2 != 3.7"


and "6 >= 9" as evaluating to "true" or "false" ("!=" means
"not equal to").
 Such expressions can be combined using the logical
(boolean) operators "&&" ("and"), "||" ("or") and "!" ("not").
 The values obtained may be summarized as follows:
 A AND B is true only when A and B are both true.
 A OR B is false only when A and B are both false.
 NOT A is true when A is false, and vice versa.

Mar 27, 202


4
40 Assignment Statements: Logical

 Symbols for AND, OR and NOT vary with
programming language.
 When complex expressions are formed using
these logical operators, parentheses may be used
as usual to indicate the preferred order of
computation.
 If parentheses are not used, the priorities NOT,
AND, OR will prevail.

Mar 27, 202


4
41 Examples
Expression: True or False:

 (6 <= 6) && (5 < 3)  false


 (6 <= 6) || (5 < 3)  true
 (5 != 6)  true
 (5 < 3) && (6 <= 6) || (5 != 6)  true
 (5 < 3) && ((6 <= 6) || (5 != 6))  false
 !((5 < 3) && ((6 <= 6) || (5 != 6)))  true

Compound Boolean expressions are typically used as the


condition in "if statements" and "for loops" (see later.) , e.g.
if (total_test_score >= 40 && total_test_score < 50)
cout << "You have just scraped through the test.\n";
Mar 27, 202
4
42 Output Statements
 The results of processing must be made
available to the user.
 With output statements, current values of
named variables are printed or otherwise
transferred to permanent storage media.
 As with input statements, there are many
formats available.
Mar 27, 202
4
43 Output Statements…
 In general, the program statement (C++):

cout << Expression1 << Expression2 << ... << ExpressionN;


will produce the screen output:

Expression1Expression2...ExpressionN
 The series of statements:

cout << Expression1;


cout << Expression2;
...
cout << ExpressionN;
will produce an identical output.
 If spaces or new lines are needed between the output expressions, these have to be included
explicitly, with a " " or a "\n" respectively. Mar 27, 202
4
44 Examples
 cout << "Enter the current year then press RETURN.\n";

 cout << "Enter your current age in years.\n";

 cout << "Enter the year for which you wish to know your age.\n";

 cout << "Your age in " << another_year << ": ";

 cout << another_age << "\n";

Mar 27, 202


4
45 Files
 This course will use input only from the keyboard, and output only to the screen.
 If programmers were restricted to use only keyboard and screen as input and output
devices, it would be difficult to handle large amounts of input data, and output data
would always be lost as soon as we turned the computer off.
 To avoid these problems, it is possible to store data in some secondary storage
device, usually magnetic tapes or discs.
 Data can be created by one program, stored on these devices (as output), and then
accessed or modified by other programs when necessary (as input).
 To achieve this, the data is packaged up on the storage devices as data structures
called files.
 The concept of files shall, however, not be discussed in this course.

Mar 27, 202


4
46 Program Marks
 These are statements that mark the beginning or
end of the program itself, or a segment of the
program.
 C++ uses { }.
 In some languages, a label, or identifier, may be
attached to designate the segment marked.
 Other options are also available (eg., BEGIN and
END).

Mar 27, 202


4
47 Exercise…..NOW

 Identify five variables


 Declare the five variables
 Put values into three of them
 Add the values in two of them, and place the result in one of the
empty two
 Add the values in two of them, and place the result in one of the
three
 Multiply the value in the last result by 7 and store the product back
 Output all values in all variables
 Give suitable comments

Mar 27, 202


4
Course Project…
48
WU Student Results Program
 (Stage 3)

 Categorize your possible WUSRP identifiers into


the various suitable data types

 (Stage 4)

 Give valid data type declarations for your


possible WUSRP identifiers

Mar 27, 202


4
Course Project…
49
WU Student Results Program

 (Stage 5)
 Input data into your appropriate WUSRP
identifiers or variables (assume initially that
there is only one student per course)

 (Stage 6)
 Write the appropriate assignment statements

Mar 27, 202


4
Course Project…
50 WU Student Results Program
 (Stage 7)
 Still assuming that there is only one student per
course, give all appropriate output results

 (Stage 8)
 Still assuming that there is only one student per
course, concatenate all your program segments so far
into one complete program

Mar 27, 202


4
51 Hurrrrrrraaaaaaayyyyy....

 Congratulations on your first


(almost) complete C++ program in
this course….

if you did not copy from


someone!!!!

Mar 27, 202


4
PROGRAM LOGIC
52

 Algorithms (steps) for large problems can be quite complex.


 An algorithm can also be exposed by using a flowchart,
which is a sort of a road map of the algorithm (not all
computer scientists like to use flowcharts, though, since they
become clumsy, at times).
 It has been found that algorithms / flowcharts developed
using three basic types of logic components are easier to
follow.
 The three “approved” components are called sequential,
conditional, and repetitive.

Mar 27, 202


4
53 SEQUENTIAL FLOW
 When a program is short, it is easily packaged up into a single list of program
statements and commands.
 The basic structure of a (C++) program is:
int main()
{
First statement;
Next statement;
...
...
Last statement;

return 0;
Mar 27, 202
4
}
54 SEQUENTIAL FLOW…
 All (C++) programs have this basic "top-level" structure.
 Notice that each statement in the body of the program ends with a
semicolon.
 In a well-designed large program, many of these statements will
include references or calls to sub-programs, listed after the main
program or in a separate file.
 These sub-programs have roughly the same outline structure as the
program here, but there is always exactly one such structure called
main.
 (You will learn more about sub-programs later.)

Mar 27, 202


4
55 SEQUENTIAL FLOW…

 In a sequential flow, as shown above, steps are


taken in an explicitly prescribed sequence.
 This is the general flow of programs.
 Steps are executed in sequence unless there is a
need to branch.
 (return statements signal that the particular sub-
program has finished, and return a value, along
with the flow of control, to the program level
above.)

Mar 27, 202


4
56 Examples: a)
 Prepare an algorithm for Fahrenheit (F) to Celsius (C) temperature conversion.
(Also write the C++ code.)

Input F
Subtract 32
Multiply by 5 Input F
Divide by 9
Output C Subtract 32

Multiply by 5

Divide by 9

Mar 27, 202


4
Output C
57 Examples: b)
 Prepare a simplified payroll.
 The hourly pay rate R, number of hours worked
H, and total deductions D for one employee are
provided.
 The gross pay G and take-home pay P are to be
calculated, records updated and a cheque printed
for the employee.
 (Also write the C++ code.)

Mar 27, 202


4
58 Examples: b) ….

Input R,H,D

Input R,H,D
G=R*H
G = R*H
P = G-D
P=G-D
Update records
Print cheque
Update Record

Print Cheque

Mar 27, 202


4
Examples: c)
59

Sample C++ code:

int year_now, age_now, another_year, another_age;


cout << "Enter the current year then press RETURN.\n";
cin >> year_now;
cout << "Enter your current age in years.\n";
cin >> age_now;

cout << "Enter the year for which you wish to know your age.\
n";
cin >> another_year;
another_age = another_year - (year_now - age_now);
cout << "Your age in " << another_year << ": "; Mar 27, 202
4

cout << another_age << "\n";


60 CONDITIONAL FLOW
 One variation to sequential flow involves a decision as to
which of various available paths is to be followed.
 In the simplest case, just two paths occur.
 To make a decision, a test is made of a condition that can be
either true or false.
 If the condition is true, then one path is taken (do steps A),
 if false, the other path is taken (do steps B).
 This logic is said to be conditional.

Mar 27, 202


4
61 Decision Flowchart
Entry

Condition
False True

Steps Steps
B A
Steps
B

Exit
Notice that the paths come together again; there is just one entry to the component,
and one exit from it. Note also that either of steps A or B may be empty. (In flowcharts,
Mar 27, 202
rectangular boxes are used for the sequential steps and diamond-shaped boxes 4 for
the decision step.)
62 Example

 A bank records each customer account transaction using a


code D for deposit and W for withdrawal. The amount of the
transaction is also specified. Prepare an appropriate algorithm
segment.
 Algorithm
Get code and amount
If code equals D
Then add amount to balance
Otherwise subtract amount

Mar 27, 202


4
Bank Account Update
63 Get Code and
Amount

Code= D
False True

Subtract Add
Amount Amount
Steps
B

Exit

Mar 27, 202


4
64 Multiple Decisions
 Naturally, this decision idea can easily be extended.
 Decisions are numerous in problems of any size.
 The diagram below shows a two-decision component.
 Exactly one of the three paths will be followed, each having its
own set of steps.
 Again, there is just one entry and one exit.
 It is therefore easy to imagine more complex decisions.

Mar 27, 202


4
65 Multiple Decisions…
Entry

Condition 1
False True

Steps False Condition 2 True


B
Steps
B
Steps Steps
A C

Mar 27, 202


4

Exit
66 Example:
 Suppose that in the bank example above, the
bank wants a safeguard against incorrect code
values (may be, due to typing errors), how
should the algorithm be modified?

 Here, another condition needs to be added; if the
code is neither D nor W, an error message is
printed and no change is made to the account.

Mar 27, 202


4
67 Example…

Algorithm

If code = D
Then add amount
Otherwise test for error
If code=W
Then subtract amount
Otherwise print error message

Mar 27, 202


4
68 Multiple Decisions…
Entry

Code=D
True False

Add True Code= W False


Amount
Steps
B
Subtract Print Error
Amount Message

Mar 27, 202


4

Exit
69 IF-THEN-ELSE Statement

 The above decision action of the conditional flow


is implemented in programming languages by
some form of IF-THEN-ELSE Statement;
 “IF a given condition is true THEN carry out
steps A, ELSE carry out steps B”.
 The condition being either true or false has the
character of a logical variable.
 Very often it will be a combination of numeric or
alphabetic variables formed using the operators:

Mar 27, 202


4
70 Conditional operators
Equals ==
Does not equal !=
Is less than <
Is less than or equal to <=
Is greater than >
Is greater than or equal to >=

 The various symbols at the right indicate ways in which


these operators are expressed. The choice depends upon
the programming language being used.

Mar 27, 202


4
71 Conditional operators…
 When these operators join numeric variables, the
usual order of numbers is assumed,
i.e., 7 < 11 is true, and 1 < 0 is false.
 When they join alphabetic variables, then the
rules for alphabetizing will be respected with
A<B<C, etc. Thus, “JANE” < “JOHN” is true.
 Examples:
 A <= BX > (Y+Z) (A <= B) || (X > (Y+Z))

Mar 27, 202


4
72 IF-THEN-ELSE Statement
 This implements the full conditional component of a program, and takes the form:

IF logical expression
(THEN) carry out steps A
ELSE carry out steps B
If the steps to be carried out in A involve more than one
statement, then the necessary statements are framed
together using the marks BEGIN and END, DO and
END, {} or ( ), depending on the programming
language.
Mar 27, 202
4
73 C++ if statement
 In C++, it is simply called an if statement, and the general
syntax is:

if (condition)
{Statement1;
...
...
StatementN;
} else
{StatementN+1;
...
...
StatementN+M;
}
Mar 27, 202
4
74 Examples:
a) if (nummaps < maxmaps)
nummaps += 1;
else
{
cout << “capacity exceeded”;
quit = true;
};
// true may have to be defined as logical before use

b) if (rate < alarm)
cout << “ time is” << time<< “ rate is” << rate;
else
cout << “alarm” << alarm <<” rate is” << rate;
Mar 27, 202
4
75 C++ if statement…
 The "else" part of an "if statement" may be
omitted, and furthermore, if there is just one
Statement after the "if (condition)", it may be
simply written as:
 if (condition)
Statement;

Mar 27, 202


4
76 Examples:
a) if (num = = goal)
found = true;

b) if (n >=) 500
{ cout << “d”;
n - = 500;
};

c) if (number > max)
{max = number;
location = count;
}; Mar 27, 202
4
Nested IF Statement
77
 It is quite common to find "if statements" strung together in programs, as follows. This is called
nesting:
 ...
if (total_test_score < 50)
cout << "You are a failure. You must study much harder.\n";
else if (total_test_score < 65)
cout << "You have just scraped through the test.\n";
else if (total_test_score < 80)
cout << "You have done quite well.\n";
else if (total_test_score < 95)
cout << "Your score is excellent. Well done.\n";
else {
cout << "You cheated!\n";
total_test_score = 0;
}
Mar 27, 202
4
...
Course Project…
78 WU Student Results Program (Stage 9)

 Still assuming that there is only one


student per course, write a complete
sequential flow program to:
 Input student’s middle initial as name
 Input course code as one character
 Input three continuous assessment marks (over 50, 30, 20)
 Compute total continuous assessment mark (over 30)
 Input final examination mark (over 100)
 Compute final examination mark (over 70)
 Find final semester mark as sum of continuous assessment and final examination
mark (over 100) Mar 27, 202
4
 Output all data (student’s full name, full course code, all marks, etc)
Course Project…
79
WU Student Results Program (Stage 10)
 Still assuming that there is only one student per course, write a
complete program to:
 Input student’s middle initial as name
 Input course code as one character
 Input three continuous assessment marks (over 50, 30, 20)
 Compute total continuous assessment mark (over 30)
 Check if this total is less than 10, give student warning
 Input final examination mark (over 100)
 Compute final examination mark (over 70)
 Check if this total is less than 25, give student warning
 Find final semester mark as sum of continuous assessment and final
examination mark (over 100)
 Categorize the final mark into grades (70+ A, 60+ B, 50+ C, 40+ D, or
Mar 27, 202
<40 F) 4
80 REPETITIVE FLOW
 The other basic variation in algorithm flow deals
with the repetition of steps.
 By developing algorithms that make efficient use
of repetition, machines can be programmed to do
very large-scale jobs.
 The diagram below shows the basic pattern.

Mar 27, 202


4
81 Repetition Flowchart
Entry

Condition
False True

Steps
A

Exit

Mar 27, 202


4
Repetition Flowchart…
82
 If the condition is true, then the steps A are taken, after which
flow is back to the condition for a possible repetition.
 As long as the condition remains true, this path is followed.

 Some step within the procedure must affect the condition.


 Otherwise repetition would continue infinitely until stopped
by a higher authority, such as the operating system.
 The path that is repeated is called a loop.
 When the condition becomes false, looping ends and the
algorithm moves forward.

 Notice that this component, like the others, has just one entry
and one exit.
Mar 27, 202
4
83 The Indexed Loop
 When the exact number of repetitions can be
specified conveniently, the indexed form of
loop control can be used; the indexed loop.
 The procedure is repeated for each
designated value of an integer variable
known as the index, (or control variable or
running variable.)

Mar 27, 202


4
Example:
84 Convert 100 Fahrenheit values to Celsius
Count = 1

True False
Count > 100

Do Convert

Increase Count

Exit
Mar 27, 202
4
85 Example:…
 In the above example, notice that Count is
initialized at one.
 This makes the governing condition false, so the
conversion steps are carried out (Convert) for the
first time.
 Count is then increased to 2, a second transit of the
loop is made, and so on.
 After the 100th execution of the procedure for the
conversion, Count goes to 101, the condition
becomes true, and exit from the loop occurs.

Mar 27, 202


4
86 The Indexed Loop…

 The indexed loop involves the use of the FOR


statement.
 The "For loop" is a repetition statement.
 It specifies how many times the loop will be
executed.
 It must always be the first statement in the loop.
 The number of executions is determined by the
index.

Mar 27, 202


4
87 The Indexed Loop…
 In most languages, the general format is:

 FOR ind = lwb TO upb BY inc

Where
ind = index or loop counter
lwb = starting value of loop counter
upb = maximum value of loop counter
inc = incremental value of loop counter
Eg:
FOR I=1 TO 100 BY 1

Mar 27, 202


4
The Indexed Loop… (C++)
88
 In C++, the general syntax is:
 for (initialisation; repetition_condition ; update)
{ Statement1;
...
...
StatementN;
}
Eg.
For (number = 32 ; number <= 126 ; number = number + 1)
{ ….. }
Mar 27, 202
4
89 The Indexed Loop… (C++)
 C++ executes such statements as follows:
(1) it executes the initialisation statement.
(2) it checks to see if repetition_condition is true. If it isn't, it
finishes with the "for loop" completely. But if it is, it executes
each of the statements Statement1 ... StatementN in turn, and
then executes the expression update.
(3) after this, it goes back to the beginning of step 2 again.

Mar 27, 202


4
90 Example code:
 int main()
{ int number;
char character;
for (number = 32 ; number <= 126 ; number = number
+ 1) {
character = number;
cout << "The character '" << character;
cout << "' is represented as the number ";

cout << number << " in the computer.\n";

}
return 0; Mar 27, 202
4

}
91 Example code:
 The above code produces the output:

The character ' ' is represented as the number 32 in the computer.


The character '!' is represented as the number 33 in the computer.
...
...
The character '}' is represented as the number 125 in the computer.
The character '~' is represented as the number 126 in the computer.

 Note from the example that if more than a single statement


is to follow the FOR, then the usual {} framing is required
in C++.
Mar 27, 202
4
92
Course Project…
WU Student Results Program (Stage 11)
 Now, let’s assume there are sixty (60) students per course, write a
complete program to do these for each of them:
 Input each student’s middle initial as name
 Input course code as one character
 Input three continuous assessment marks (over 50, 30, 20)
 Compute total continuous assessment mark (over 30)
 Check if this total is less than 10, give student warning
 Input final examination mark (over 100)
 Compute final examination mark (over 70)
 Check if this total is less than 25, give student warning
 Find final semester mark as sum of continuous assessment and final
examination mark (over 100)
 Categorize the final mark into grades (70+ A, 60+ B, 50+ C, 40+ D, or
<40 F) Mar 27, 202
4
 Output all data (student’s full name, full course code, all marks, etc)
93 The WHILE Statement
 One other basic way for implementing the loop component
of a program is the WHILE statement.
 This is used when the exact number of repetitions cannot be
specified in advance.

 It is equivalent to:
 “While the governing condition remains true, carry out the
given procedure”, i.e.,
 while a logical expression remains true, a given procedure
will be carried out.
Mar 27, 202
4
94 The WHILE Statement…
 The above statement may be put as:

 While the condition is true


Execute the procedure or steps and
Return to the condition

 Actually, any "for" loop can be re-written as a "while" loop. Similarly, any
"while" loop can also be written as a "for" loop.

 For example, the last program code can be written equivalently as follows:

Mar 27, 202


4
The WHILE Statement… example
95

 int main()
{ int number;
char character;
number = 32;
while (number <= 126)
{
character = number;
cout << "The character '" << character;
cout << "' is represented as the number ";
cout << number << " in the computer.\n";
number++;
}
return 0; Mar 27, 202
4
}
96 Do ... while
 There is a third kind of "loop" statement (in C++,
etc) called a "do ... while" loop (or
REPEATUNTIL statement in some other
languages).
 These differ from the "for" and "while" loops in
that the statement(s) inside the {} braces are
always executed once, before the repetition
condition is even checked, ie,
 the system performs the steps before testing the
condition.

Mar 27, 202


4
97 Nested Loops
 It is possible to have loops within loops (to several levels). This is called
nesting.
 The rules for writing single loops apply to nested loops.
 In addition, the following restrictions must be observed:
1. Each nested loop must begin with its own FOR statement.
2. An outer loop and an inner loop cannot have the same index.
3. Each inner loop must be completely embedded within an outer loop, i.e.,
no overlaps.
4. Control can be transferred from an inner loop to a statement in an outer
loop or to a statement outside the entire nest. However, control cannot
be transferred to a statement within a nest from outside the nest.

Mar 27, 202


4
98
Nested Loops…

 Thus, we may have:

FOR (….)
{ FOR (….)
{
…….
}
};

Mar 27, 202


4
99 The (Controversial) GO TO
 Another method of controlling the flow of processing has long been the GO TO
statement.
 It exists in more or less the same form in most programming languages and simply
indicates the statement that is to be executed next.
 By using GO TO’s, programmers divert program flow at will and easily get
problems solved.

 The GO TO statement simply takes the form:
GO TO label
where label is the statement number of the next statement to be executed.

Mar 27, 202


4
100 The (Controversial) GO TO…
 Also called the “Jump Statement” because of
its action, the GO TO has now lost its appeal
in almost all programming languages.
 This is because, too liberal use of the GO TO
statement makes a program jump around so
much that it becomes difficult to follow.
 It is therefore advisable to avoid GO TOs.

Mar 27, 202


4
Remarks about Program Style
101

 As far as the C++ compiler is concerned, the


following two program codes are exactly the
same.

Program A
 int main(){ int year_now, age_now, another_year, another_age; cout <<
"Enter the current year then press RETURN.\n"; cin >> year_now; cout
<< "Enter your current age in years.\n"; cin >> age_now; cout <<
"Enter the year for which you wish to know your age.\n"; cin >>
another_year; another_age = another_year - (year_now - age_now); if
(another_age >= 0) { cout << "Your age in " << another_year << ": ";
cout << another_age << "\n"; } else { cout << "You weren't even born
in "; cout << another_year << "!\n"; } return 0; } Mar 27, 202
4
Program B)
102  int main()
 { // This is the better of the two programs
 int year_now, age_now, another_year, another_age;

 cout << "Enter the current year then press RETURN.\n";
 cin >> year_now;

 cout << "Enter your current age in years.\n";
 cin >> age_now;

 cout << "Enter the year for which you wish to know your age.\n";
 cin >> another_year;

 another_age = another_year - (year_now - age_now);

 if (another_age >= 0) {
 cout << "Your age in " << another_year << ": ";
 cout << another_age << "\n";
 } else {
 cout << "You weren't even born in ";
 cout << another_year << "!\n";
 }
Mar 27, 202
 return 0; 4

 }
103 Remarks about Program Style…

 However, the lack of program comments, spaces, new lines and


indentation makes the A) program unacceptable.
 There is much more to developing a good programming style than learning
to lay out programs properly, but it is a good start!
 Be consistent with your program layout, and make sure the indentation and
spacing reflects the logical structure of your program.
 It is also a good idea to pick meaningful names for variables; "year_now",
"age_now", "another_year " and "another__age " are better names than
"y_n", "a_n", "a_y" and "a_a", and much better than "w", "x", "y" and "z".
 Remember that your programs might need modification by other
programmers at a later date.

Mar 27, 202


4
An Example Complete C++
104
Program
// The C++ compiler ignores comments which start with
 // double slashes like this, up to the end of the line.

 /* Comments can also be written starting with a slash
 followed by a star, and ending with a star followed by
 a slash. As you can see, comments written in this way
 can span more than one line. */

 /* Programs should ALWAYS include plenty of comments! */

 /* Author: Rob Miller and William Knottenbelt
 Program last changed: 30th September 2001 */
 /* This program illustrates several general features of all C++ programs. */
 // For further details, consult your C++ lecturer Mar 27, 202
4
105 Complete C++ Program…
 /* This program prompts the user for the current year, the user's
 current age, and another year. It then calculates the age
 that the user was or will be in the second year entered. */

 #include <iostream>

 using namespace std;

 int main()
 {
 int year_now, age_now, another_year, another_age;

 cout << "Enter the current year then press RETURN.\n";
 cin >> year_now;

 cout << "Enter your current age in years.\n"; Mar 27, 202
4
 cin >> age_now;
106 Complete C++ Program…
cout << "Enter the year for which you wish to know your
age.\n";
 cin >> another_year;

 another_age = another_year - (year_now - age_now);

 if (another_age >= 0) {
 cout << "Your age in " << another_year << ": ";
 cout << another_age << "\n";
 } else {
 cout << "You weren't even born in ";
 cout << another_year << "!\n";
 }

 return 0; Mar 27, 202
4
 }
Course Project…
107 WU Student Results Program (Stage 12)

 Now, we don’t know the exact number of students per course.


We only know of a terminator after the last name. Write a
complete program to do these for each student:
 Input each student’s middle initial as name
 Input course code as one character
 Input three continuous assessment marks (over 50, 30, 20)
 Compute total continuous assessment mark (over 30)
 Check if this total is less than 10, give student warning
 Input final examination mark (over 100)
 Compute final examination mark (over 70)
 Check if this total is less than 25, give student warning
 Find final semester mark as sum of continuous assessment and final
examination mark (over 100)
 Categorize the final mark into grades (70+ A, 60+ B, 50+ C, 40+ D, or <40 F)
 Output all data (student’s full name, full course code, all marks, etc)
Mar 27, 202
4
Course Project…
108
WU Student Results Program (Stage 13)
 Now, assume again there are sixty (60) students per course, write a
complete program to do these using SWITCH:
 Input each student’s middle initial as name
 Input course code as one character
 Input three continuous assessment marks (over 50, 30, 20)
 Compute total continuous assessment mark (over 30)
 Check if this total is less than 10, give student warning
 Input final examination mark (over 100)
 Compute final examination mark (over 70)
 Check if this total is less than 25, give student warning
 Find final semester mark as sum of continuous assessment and final
examination mark (over 100)
 Using the IF statement, categorize the final mark into grades (70+ A, 60+ B,
50+ C, 40+ D, or <40 F) Mar 27, 202
4
 Output all data (student’s full name, full course code, all marks, etc)
109 ARRAYS

 The topic of Arrays may be discussed under three subsections:

 Array Philosophy
 Array Declaration
 Array Use

Mar 27, 202


4
110
Array Philosophy

 It is often necessary to deal with lots of variables, which have


something in common, in a single processing job.
 Naturally we may arrange them into one or more lists, all
variables in a given list being of the same type.
 For example, the names of a bank’s customers form a list, their
current balances form another list.
 We might want to write a program that inputs and then ranks
or sorts these long lists of numbers and names.

Mar 27, 202


4
Array Philosophy…
111

 Programming languages (including C++) provide a structured


data type called an array to facilitate this kind of task.
 The use of arrays permits us to set aside a group of memory
locations (i.e. a group of variables) that we can then
manipulate as a single entity, but that at the same time gives us
direct access to any individual component.
 Arrays are simple examples of structured data types - they are
effectively just lists of variables all of the same data type
("int", "char" or whatever).

Mar 27, 202


4
Array Philosophy…
112

 The identifier ITEM, for example, can stand for a list of items
in a warehouse while ITEM(1), ITEM(2), ITEM(3)…
represent the first, second, third, and other individual items in
that list.
 The integers (I=1,2,3…) within the parentheses are called
subscripts.
 Variables of this sort; ITEM(1), ITEM(2), ITEM(3)…, are
called subscripted variables.
 Since one subscript is enough to designate a particular value,
they are also known as one-dimensional arrays.

Mar 27, 202


4
Array Philosophy…
113
All programming languages include special procedures for handling subscripted
variables, but there are some general principles.

 Subscripts are always integers and may be required to be positive.


 A name that identifies an array may not be used for another
variable, i.e. D(I) and D may not be permitted in the same
program.
 The maximum number of elements in the array (dimension) must
be declared. This causes the compiler to reserve adequate storage
space for the array. (It is wise, however, to reserve slightly more
than required!)
 Subscripted subscripts such as D(I(J)) may or may not be
allowed.
 Subscripts may be arithmetic expressions, e.g., D(2*A-B)
 Once declared, each element can then be used as any ordinary Mar 27, 202
4

variable.
114 Array Declaration
 As stated above, arrays have to be declared before use in a program.
 This causes the compiler to reserve adequate storage space for them.

 The syntax for an array declaration in C++ is:


<component type> <variable identifier>[<integer value>];

Eg. int hours[6]

Mar 27, 202


4
115 Example Array Declaration:
 Suppose we are writing a program to manipulate
data concerning the number of hours a group of 6
employees have worked in a particular week.
 We might start with the array declaration:
int hours[6];
 In each case, we end up with 6 variables of type
"int" with identifiers
 hours[0] hours[1] hours[2]
hours[3] hours[4] hours[5]

Mar 27, 202


4
116 Example Array Declaration:
 Each of these is referred to as an element or
component of the array.
 Thus hours[3] is the third element of the array
hours.
 As stated earlier, the numbers 0, ..., 5 are the
indexes or subscripts of the components.
 An important feature of these 6 variables is that
they are allocated consecutive memory locations
in the computer.

Mar 27, 202


4
117 Array Use
 Having declared our array, we can treat the
individual elements just like ordinary
variables (of type "int" in the particular
example above).

 We can have assignment statements and


expressions with the array elements.

Mar 27, 202


4
Array Use…
118

 We can write assignment statements such as


hours[4] = 34;
hours[5] = hours[4]/2;
and use them in logical expressions, e.g.
if (number < 4 && hours[number] >= 40) { ...

A common way to assign values to an array is using a "for" or "while"


loop.

Mar 27, 202


4
119 Strings
 We have already been using string values, such
as ""Enter age: "", in programs involving output
to the screen.

 In C++ and many other languages, you can store


and manipulate such values in string variables,
which are really just arrays of characters, but
used in a particular way.

Mar 27, 202


4
120 String Variable Declarations and
Assignments

 String variables can be declared just like other


arrays:
 char phrase[14];
 String arrays can be initialised or partially
initialised at the same time as being declared,
using a list of values enclosed in "{}" braces (the
same is true of arrays of other data types).

Mar 27, 202


4
121 Strings…
 For example, the statement
char phrase[14] = {'E','n','t','e','r',' ','a','g','e',':',' ','\0'};
both declares the array "phrase" and initialises it.

 The statement
char phrase[14] = "Enter age: ";
is equivalent.

Mar 27, 202


4
122 Strings…
 If the "14" is omitted in the last example, an array will be
created just large enough to contain both the value ""Enter age:
"" and the sentinel character "'\0'",
 So the two statements
 char phrase[] = {'E','n','t','e','r',' ','a','g','e',':',' ','\0'};
 char phrase[] = "Enter age: ";

are equivalent to each other and to the statement


 char phrase[12] = "Enter age: ";

Mar 27, 202


4
123 Strings… in C++
 However, it is important to remember that in C+
+ string variables are arrays,
 so we cannot just make assignments and
comparisons using the operators "=" and "==".
For example, we cannot simply write
phrase = "You typed: ";
 Instead, we can use a special set of functions for
string assignment and comparison.

Mar 27, 202


4
Course Project…
124
WU Student Results Program (Stage 14)

Assume again there are sixty (60) students per course.


 Give valid array declarations for the :
 Students names (middle initials only)
 Each continuous assessment marks (three of them!)
 Final continuous assessment marks (over 30)
 Final exam marks (over 100)
 Final exam marks (over 70)
 Final semester marks (over 100)
 Final grade awarded for the course
Mar 27, 202
4
Course Project…
125 WU Student Results Program
 (Stage 15)
 Assume again there are sixty (60) students per course.
 Input data into these your arrays:
 Students names (middle initials only)
 Each continuous assessment mark (three of them!)
 Final exam mark (over 100)

 (Stage 16)
 Give an array declaration for the Course Codes
 Input data into the declared Course Code array
Mar 27, 202
4
Course Project…
126
WU Student Results Program (Stage 17)
 Now, assume again there are sixty (60) students per course, write
a complete program to do these using arrays and IF statements:
 Input each student’s middle initial as name
 Input course code as one character
 Input three continuous assessment marks (over 50, 30, 20)
 Compute total continuous assessment mark (over 30)
 Check if this total is less than 10, give student warning
 Input final examination mark (over 100)
 Compute final examination mark (over 70)
 Check if this total is less than 25, give student warning
 Find final semester mark as sum of continuous assessment and final
examination mark (over 100)
 Output all data (student’s full name, full course code, all marks,Mar
4 etc)
27, 202
SUBPROGRAMS
127
The Need for Sub-programs

 A natural way to solve large problems is to break them down


into a series of sub-problems, which can be solved independently
and then combined to arrive at a complete solution.
 It is also often convenient to give names to some parts of a
program, and refer to them by the names right through the
program.
 The program then consists of parts, which may be called
subprograms, subroutines, procedures, or modules.
 In a long program, the use of subroutines is very essential, but
they can be useful even in short programs too.
 They improve program readability, since each part is more brief.
Mar 27, 202
4
Top Down Design and Procedural
128
Abstraction

 One of the main purposes of using subprograms is to aid in the top


down design of programs.
 During the design stage, as a problem is subdivided into tasks (and
then into sub-tasks, sub-sub-tasks, etc.), the problem solver
(programmer) should have to consider only what a subprograms is
to do and not be concerned about its details.
 The subprograms name and comments at the beginning of the
function should be sufficient to inform the user as to what the
function does.
 Developing functions in this manner is referred to as procedural
abstraction.
Mar 27, 202
4
Top Down Design and Procedural
129
Abstraction…
 Indeed, during the early stages of program
development, experienced programmers often
use simple "dummy" functions or stubs, which
simply return an arbitrary value of the correct
type, to test out the control flow of the main or
higher level program component.

 Subprograms can be developed in a number of


ways. Some are called internal, others external.

Mar 27, 202


4
Internal Subprograms
130
 Internal subprograms are listed within the main program.
Thus:

 Main program;
 ……
 Call subprogram 1;
 Call subprogram 2;
 ……
 Subprogram 1;
 …..
 End;
 Subprogram 2;
 …...
 End; Mar 27, 202
4

 End of main program;


131 Internal Subprograms …
 As parts of the main program, the variables that these
subprograms operate with are largely those of the main
program.
 Variables borrowed from the main program are called global
variables; since they are (globally) available to all parts of the
program.
 Other variables may be created for use strictly within a
subprogram; these are called local variables.
 The scope of global variables is the entire program whereas
the scope of local variables is the subprogram for which they
are created.
Mar 27, 202
4
132 External Subprograms
 These are independent programs, compiled and tested separately and perhaps
available for general use, as library routines are. Thus;

 Main program;
 ……
 Call subprogram 1(A, B, C);
 ……
 End of main program;

 Subprogram 1(X, Y, Z);
 ……
 End;
Mar 27, 202
4
133 External Subprograms …
 Here, the independent nature of subprogram 1 is shown by its
placement outside of the main program.
 Communication between main program and subprogram is
done by listing within each subprogram a number of
parameters or dummy variables (such as X, Y, Z above),
 and then providing in the calling statement of the main
program the actual arguments or values (A, B, C) which are
passed on to the dummies.
 When the subprogram is executed, these actual values will be
used.
 This makes it possible to use the subprogram several times
with different arguments. Mar 27, 202
4
Course Project…
134
WU Student Results Program (Stage 18)
 Now, assume again there are sixty (60) students per
course, modify your program of Stage 17 into
subprograms

Mar 27, 202


4
PROGRAM ERRORS
135 Syntax and Semantics
 Programming involves the two concepts of syntax and
semantics.
 Semantics deals with understanding the logic of the
problem at hand, and
 Syntax involves knowing and fully obeying the rules of
the selected programming language for solving the
problem.
 Semantic errors occur when the programmer is unable to
fully understand the logic of the problem… and this often
leads to execution errors or wrong solutions from
programs (see later).
Mar 27, 202
4
Syntax Errors
136
 One large source of program errors is the misuse of the
programming language, either by ignorance of the language
rules, carelessness or keyboard typing errors.
 These grammatical errors are called syntax errors.
 Syntax errors are common, but are easier to find and correct.
 Many will be conspicuous to the programmer and others are
pointed out by the compiler (also called compilation errors).
 Syntax errors usually prevent execution (running) of the
program from even starting.

Mar 27, 202


4
Execution Errors
137

 Other kinds of program errors may allow execution to begin


but cause it to terminate prematurely, often producing an error
message.
 Among these are:
 “Bad data”: input to be supplied for reading, either absent or not
in a form consistent with what the program calls for
 Bad parameters: values passed to subroutines not being of the
expected type or sufficient quantity
 Bad values: numerical values exceeding expected limits.

Mar 27, 202


4
Execution Errors…
138

 Still some kinds of error will allow a program to run


normally but produce no output at all, or output that is
clearly wrong. Dangerous!
 Far more dangerous are errors that allow a program to
execute and generate output that to superficial
inspection seems reasonable but are not totally
correct.
 All these errors that occur during the running of the
program are called execution or run-time errors.
 Many execution errors are due to semantic / logic
problems!!!
Mar 27, 202
4
Program Testing
139

 Owing to the above program errors, it is therefore essential


that programs be subjected to planned rigorous testing
procedures.
 Output should be checked with whatever supporting
information is available.
 Full understanding of the original problem is vital here, since
the goal is to decide:
 a) whether the program correctly implements the algorithm
and
 b) whether the algorithm correctly solves the problem, in the
first place.
Mar 27, 202
4
Suggestions for program testing
140

1. Test subprograms separately. This is in the spirit of top-down


analysis, which breaks a problem into segments. Being smaller, the
segments are usually easier to test than the complete program.
2. Choose test data that brings all parts of the program into action.
This enables all program paths to be tested.
3. Test simple cases for which exact answers are known. This will not
prove the program correct but may detect gross errors very quickly.
4. Generate extra output during the testing phase (by including lots of
output statements). This makes it possible to trace the flow of
processing. If requested output is not produced at a certain stage, it
means flow did not reach the point where the request was made. If a
loop is involved, it should be tested to find out if the correct
number of loops has been completed. The extra output statements
are then removed when testing has been completed.
Mar 27, 202
4
Exercise…..NOW
141  Identify five variables
 Declare the five variables
 Repeat the following steps ten times
 Put values into three of your five variables
 Add the values in two of them, and place the result in one of the empty
two
 Add the values in two of them, and place the result in one of the three
 Multiply the value in the last result by 17 and store the product back
 Check if the product is greater than 500 and say so, otherwise double it
 Output all values in all variables
 Give suitable comments on this exercise
 Give a statement that you are now comfortable with basic
programming principles, and therefore, ready for any examination on
them

Mar 27, 202


4
Exercise…..NOW
142  Declare three variables
 Repeat the following steps fifteen times
 Put values into two of your three variables
 Add the values in those two of them, and place the result back in one of
the two
 Multiply the value in the last result by 15 and store the product back
 Check if the product is greater than 50 and say so, otherwise double it
 Multiply the value in the last variable by 5 and store the product back
 Check if the result is > than 80, print the word Excellent, if < 40, print
the words Too Bad
 Output all values in all variables
 Give suitable comments on this exercise
 Give a statement that you are now comfortable with basic
programming principles, and therefore, ready for any examination on
them
Mar 27, 202
4
Exercise…..NOW….Preferably
143
Individually
 Declare four variables; two integer, two decimal
 Repeat the following steps fifty times
 Put values into your variables
 Multiply the values in the two integer variables, and place the result back in
one of the two
 Multiply the value in the last result by 5 and store the product back
 Check if the product is <=20 and say so, otherwise double it
 Multiply the value in the last variable by 1.5 and store the product in one of
your floating point variables
 Categorize the last product as into grades (70+ A, 60+ B, 50+ C, 40+ D, or
<40 F)
 Check if the grade is A, print the word Excellent; if F, print the words Too
Bad
 Output all values in all variables
 Give suitable comments on this exercise
 Give a statement that you are now very comfortable with basic
programming principles, and therefore, ready for any examinationMaron
27, 202
4
them
144 Further Programming…
 Various programming languages and more advanced
topics will be studied after this course.
 We hope this course will make you enjoy programming,
even if ultimately you will end up being a rice or spare-
parts dealer.

 Thank you.

You might also like