CSC2305 FIRST LECTURE NOTE
CSC2305 FIRST LECTURE NOTE
CSC2305
FOUNDATION OF SEQUENTIAL PROGRAMS
Lecture Note
1
CSC2305 FOUNDATIONS OF SEQUENTIAL PROGRAM: (3units)
The relationships between H/L languages and the Computer Architecture that
underlies their implementation: basic machine architecture, assembles
specification and translation of P/L Block Structured Languages, parameter passing
mechanisms.
2
artificial intelligence, as well as the development of new languages that target
specific domains or platforms.
High-level programming languages can be classified into several categories based
on various criteria such as purpose, paradigm, and level of abstraction. Here are
some common classifications of high-level programming languages:
Purpose: High-level programming languages can be classified based on their
primary purpose or application domain. For example, there are programming
languages designed for scientific computing and data analysis, such as Python and
R. There are also programming languages designed for web development, such as
JavaScript, PHP, and Ruby. Additionally, there are programming languages designed
for mobile app development, game development, and enterprise applications, such
as Java, Swift, and C#.
Paradigm: High-level programming languages can also be classified based on their
programming paradigm or style. The main programming paradigms include
procedural, object-oriented, functional, and declarative programming. Procedural
languages, such as C and Pascal, are focused on procedures or subroutines that
perform specific tasks. Object-oriented languages, such as Java and Python, focus
on objects that encapsulate data and behavior. Functional languages, such as
Haskell and Lisp, focus on functions and expressions that can be combined to create
programs. Declarative languages, such as SQL and Prolog, focus on specifying what
a program should do, rather than how to do it.
Level of Abstraction: High-level programming languages can also be classified
based on their level of abstraction or closeness to machine language. The level of
abstraction can be low, such as assembly language, or high, such as Python or Ruby.
Low-level languages provide direct control over hardware resources and offer high
performance, but are difficult to use and require more expertise. High-level
languages provide more abstraction and are easier to use, but may be less efficient
and offer less control over hardware resources.
Implementation: High-level programming languages can also be classified based on
their implementation or execution model. Compiled languages, such as C and C++,
are compiled into machine code before execution, resulting in faster performance
but requiring separate compilation for each platform. Interpreted languages, such
as Python and Ruby, are interpreted by an interpreter at runtime, resulting in slower
3
performance but better platform independence. There are also hybrid languages,
such as Java and C#, that are compiled into an intermediate language and then
interpreted or just-in-time compiled at runtime.
Basically, it means 2 thousand, 1 hundred, 5 Tens and 3 Units. This could also be
expressed in the powers of 10 as follows:
Number 2 1 5 3
Place Holder 103 102 101 100
Result 2 * 103= 1 * 102 = 100 5 * 101 = 3 * 100 = 3 Total
2,000 50 =2,153
4
In the decimal system the place-holder for each digit is a power of 10 so that moving
from right to left, in the table, corresponds to an increase in magnitude by a factor
of 10 at every step.
Binary Numbers
According to digital electronics and mathematics, a binary number is defined as a
number that is expressed in the binary system or base 2 numeral system. It
describes numeric values by two separate symbols; 1 (one) and 0 (zero). The base-
2 system is the positional notation with 2 as a radix.
The binary system is applied internally by almost all latest computers and computer-
based devices because of its direct implementation in electronic circuits using logic
gates. Every digit is referred to as a bit. We have seen that in base 10 every number
can be written as a weighted sum of powers of 10. In an analogous manner for base
2 we use a weighted sum of powers of 2 to express numbers. The place-holder for
each digit is therefore a power of 2 and moving from right to left corresponds to an
increase in magnitude by a factor of 2 at every step. For example, consider the
following table.
Place Holder 23 22 21 20
Weight 8 4 2 1
Binary Digit 1 0 1 1
The binary number in the table, 1101 is sometimes written with the subscript “2”
to indicate that it is a base 2 number, i.e. 11012. To obtain the decimal
representation of 1101 we multiply each binary digit by its column’s weight and
sum the values. Starting from the right,
5
Octal Numbers
Octal numbers are numbers to base 8. There are eight symbols used in the octal
system, 0, 1, 2, 3, 4, 5, 6, and 7. Its place holder increase in powers of 8. Octal
numbers are used as a shorthand for binary. Octal used to be popular when
computers employed 12-bit, 24-bit or 36-bit words for data and addressing.
However, as modern computers all use 16-bit, 32-bit or 64-bit words octal is rarely
used nowadays. Consider the table given below:
The octal number in the table, 573 is sometimes written with the subscript “8” to
indicate that it is a base 8 number, i.e. 5738. To obtain the decimal representation
of 573 we multiply each octal digit by its column’s weight and sum the values.
Starting from the right,
3*80 + 7*81 + 5*82 = 3 + 56 + 320 = 379
Hence 5738 = 37910
Hexadecimal
The hexadecimal (often called hex) or base 16 number system uses sixteen symbols,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, to represent numbers. The first ten digits are
the same as in the decimal system while the remaining six, A to F, correspond to the
numbers from 10 to 15 respectively.
A computer carries out all its operations in binary but as numbers become large the
binary representation requires increasingly more digits (0’s and 1’s) and becomes
difficult for humans to read and write. For this reason, computers often display
information, such as memory addresses, in hexadecimal as their format is more
compact.
In base 16 we use a weighted sum of powers of 16 to express numbers. The
placeholder for each digit is therefore a power of 16 and moving from right to left
6
corresponds to an increase in magnitude by a factor of 16 at every step. Consider
the table given below:
The hex number in the table, 23CF can be written with the subscript “16”, to
indicate that it is a base 16 number, i.e. 23CF16.
To obtain the decimal representation of 23CF16, we multiply each hex digit by its
column’s weight, noting that C represents 12 and E corresponds to 14, and sum the
values, i.e.
(14*1) + (12*16) + (3*256) + (2*4096) = 9166 Hence 23CE16 = 916610
After looking at how to convert other bases to base 10 now let look at Converting
from base 10 (decimal) to any other base which is easy. Start with the decimal
number to be converted and repeatedly divide by the new base number retaining
the remainder at each step. We shall illustrate with some examples.
Decimal to Binary
We can convert the given decimal to binary using different methods such as
formula, division method, and so on. In the section, you will learn how to convert
decimal numbers to binary in the division method. To convert decimal to binary
numbers, proceed with the steps given below:
Step 1: Divide the given decimal number by “2” where it gives the result along
with the remainder.
Step 2: If the given decimal number is even, then the result will be whole and it
gives the remainder “0”
Step 3: If the given decimal number is odd, then the result is not divided properly
7
and it gives the remainder “1”.
Step 4: By placing all the remainders in order in such a way, the Least Significant
Bit (LSB) at the top and Most Significant Bit (MSB) at the bottom, the required
binary number will be obtained.
Now, let us convert the given decimal number 294 into a binary number.
Question:
Convert 195.25 into binary.
Solution:
195 / 2 = 97 with remainder 1
97 / 2 = 48 with remainder 1
48 / 2 = 24 with remainder 0
8
24 / 2 = 12 with remainder 0
12 / 2 = 6 with remainder 0
6 / 2 = 3 with remainder 0
3 / 2 = 1 with remainder 1
1 / 2 = 0 with remainder 1
Thus, the binary equivalent of 19510 is 110000112.
Now, we have to convert the fractional part of the given number into binary.
Multiply 0.25 by 2 and observe the resulting integer and fractional parts. Renew
multiplying the resultant fractional part by 2 until we get a resulting fractional part
equal to zero.
Then we need to write the integer parts from the results of each multiplication to
make the equivalent binary number.
0.25 × 2 = 0 + 0.5
0.5 × 2 = 1 + 0
Here, 0.25 is equivalent to the binary number 0.01.
Therefore, (195.25)10 = (11000011.01)2
Decimal to Octal
Follow the steps given below to learn the decimal to octal conversion:
1. Write the given decimal number
2. If the given decimal number is less than 8 the octal number is the same.
3. If the decimal number is greater than 7 then divide the number by 8.
4. Note the remainder, we get after division
5. Repeat step 3 and 4 with the quotient till it is less than 8
9
6. Now, write the remainders in reverse order (bottom to top)
7. The resultant is the equivalent octal number to the given decimal number.
Decimal to Hexadecimal
The conversion of decimal numbers to hexadecimal numbers is a very easy task. It
can be done with the help of a conversion table. If one memorizes this table, he/she
can easily convert a decimal number to a hexadecimal number. For the decimal
numbers from 1 to 15, there is an equivalent hexadecimal number. But how to
convert the decimal number if it is more than 15. Then we need to follow a different
procedure.
If any given number is more than 15, then we have to divide the decimal number
by 16 and consider the remainder to get the equivalent hexadecimal number. The
complete procedure we have explained here step by step. But before learning the
steps let us see the table, where for each value of the decimal number from 0 to
15, there is an equivalent hexadecimal number given.
To convert the decimal number system to hex, students have to remember the
table given below, to solve the problems in a quick way.
10
Go through the steps given below to learn how to convert the numbers from
decimal to hex.
Step 1: First, divide the decimal number by 16, considering the number as an
integer.
Step 2: Keep aside the remainder.
Step 3: Again, divide the quotient by 16 and repeat till you get the quotient value
equal to zero.
Step 4: Now take the values of the remainder’s left in the reverse order to get the
hexadecimal numbers.
Note: Remember, from 0 to 9, the numbers will be counted as the same in the
decimal system. But from 10 to 15, they are expressed in alphabetical order such as
A, B, C, D, E, F and so on.
Let us take an example to understand the steps given above for decimal to hex
conversion.
Example: Convert 122810 into hex.
Solution:
11
Binary Addition
• Similar to addition of decimals
• add digits from right to left
• include carry
111
1 0 12 510
+ 0 1 12 +310
10 0 02 810
➢ Add the following
1. 110110 +101010,
2. 11101110 + 10110
3. 11011 +1111100
➢ Subtraction of Binary Numbers
1. 1111 – 1010
2. 1100 – 1011
3. 11001101 – 11001010
Two Issues
1. Fixed width (i.e. n-bit representation) means the possibility of overflow:
answer can take more than n bits to represent.
2. How do we represent negative numbers
12
• fixed width n-bit representation
- most significant bit (MSB): left-most (highest value)
- least significant bit (LSB): right-most (lowest value)
14
Example 2: 6-7
0111 7
1000 invert 7
0001 add 1 to the first comp
1001 -7 in 4-bit 2’s comp
0110 6
+1001 +(-7)
01111 -1
ignore last carry bit
exercise: use 8-bit 2’s complement to solve the following
1. 9-4
2. -13+5
3. 20 – 15
4. 100 – 50
5. 30 – 40
6. – 17 – 18
7. -6+6
Numbers: Overflow
Example 3: 5 + 3
5 + 3 = overflow error in 4-bit two’s complement
0101 5
15
+0011 +3
1000 -8
• If two positive integers are added together and the result is negative,
this
change in sign indicates an overflow error.
• When adding 5 + 3, there is overflow in Example 3.
• You can also have overflow when you add two negative numbers and
get a positive one.
PRINCIPLES OF PROGRAMMING
What is Programming?
Because computers do not understand natural languages such as English, they must
be programmed in special computer languages before they can perform any task.
Programming is the process of creating a series of instructions known as programs
that will be given to a computer to perform a specific task. Despite being regarded
as a super machine, computers cannot solve any problem that has not been
directed to them by humans (Programmers). It is more accurate to say that
computer intelligence is derived from human intelligence (garbage in garbage out).
To design, develop, test, implement, or maintain computer programs, a
programmer needs some basic facilities and tools. Text editors, compilers,
interpreters, diagnostic tools, and other tools are examples of these facilities and
tools. Text editors provide the fundamental means of creating and modifying text
files, as well as the ability to open, view, and edit plain text. Notepad, E-TextEditor,
GNU Emacs, EditPlus, gedit, Textpad, UltraEdit, and other programs are examples.
A compiler is a special program that converts statements written in a programming
language into machine language or "code" that a computer's processor can use. An
interpreter is a program that executes instructions written in a programming or
16
scripting language(Designed for specific tasks) without first converting them to
object code or machine code. Perl, Python, and Matlab are all examples of
interpreted languages. Diagnostic tools are used to detect error messages in a
programmer's source code that refer to statements or syntax that the compiler does
not understand. These tools for editing, compiling, debugging, and so on are
sometimes combined in a single graphical user interface. This integrated tool is
known as an Integrated Development Environment (IDE), and it is used for rapidly
developing computer programs. Visual Studio, NetBeans, JBuilder, and Eclipse are a
few examples.
17
Program Development Life Cycle
A set of steps is followed when creating a computer program in any programming
language. In program development, these steps are referred to as phases. To
successfully develop correct computer programs, this sequence of steps must be
carefully followed. The process of creating computer programs is known as the
program development life cycle (PDLC). The program development life cycle is a
series of steps or phases that must be followed in order to create a program in any
programming language. PDLC is a method for developing high-quality software in a
systematic manner. It provides an organized plan for breaking down the task of
program development into manageable chunks, each of which must be completed
successfully before proceeding to the next phase. The program development
process is divided into the following steps:
1. Problem Definition
The first step is to define the problem. In major software projects, this is a job for
system analyst, who provides the results of their work to programmers in the form
of a program specification. The program specification defines the data used in
program, the processing that should take place while finding a solution, the format
of the output and the user interface. In this phase, the problem statement is defined
and the boundaries of the problem are decided. In this phase there is need to
18
understand the problem statement, what is the requirement, and what should be
the output of the problem solution. These are defined in this first phase of the
program development life cycle. The developers must obtain the program
requirements from the users and document the requirements. Typically, a standard
form is used to develop the requirements.
A programmer is usually given specification of what proposed program is required
to do. The programmer must then design and implement the program so that it
meets the specification. A program that meets its specification is said to be correct.
An important factor in determining program specification is to produce
requirements specification. A system analyst will discuss the requirements
specification with the users. A requirement is simply a statement of what the
system must do or what characteristics it needs to have. During a systems
development project, requirements will be created that describe what the business
needs (business requirements); what the users need to do (user requirements);
what the software should do (functional requirements); characteristics the system
should have (nonfunctional requirements); and how the system should be built
(system requirements).
2. Problem Analysis
During analysis, a programmer review specification to fully understand what the
software should do. The analysis of the problem to be solved involves having the
basic understanding of the problem, identification and designing of inputs and
outputs and identification of any suitable solution model. The requirements like
variables, functions, etc. to solve the problem are determined in this phase. That
means the required resources to solve the problem defined in the problem
definition phase are gathered in this phase.
3. Algorithm Development
During this phase, a step by step procedure to solve the problem using the
specification given in the previous phase is developed. This phase is very important
for program development. That means we write the solution in step by step
statements. Program design starts by focusing on the main goal that the program is
trying to achieve and then breaking the program into manageable components,
each of which contributes to this goal. This approach of program design is called
top-bottom program design or modular programming. The first step involves
19
identifying main routine, which is the one of program’s major activity. From that
point, programmers try to divide the various components of the main routine into
smaller parts called modules. For each module, programmer draws a conceptual
plan using an appropriate program design tool to visualize how the module will do
its assign job.
The various program design tools are described below:
i. Algorithms An algorithm is a step-by-step description of how to arrive at a
solution in the easiest way. Algorithms are not restricted to computer world
only. In fact, we use them in everyday life.
ii. Flowcharts A flowchart is a diagram that shows the logic of the program.
iii. Pseudo-code A pseudo-code is another tool to describe the way to arrive at
a solution. They are different from algorithm by the fact that they are
expressed in program language like constructs.
4. Coding and Documentation
This phase uses a programming language to write or implement the actual
programming instructions for the steps defined in the previous phase. In this phase,
we construct the actual program. That means we write the program to solve the
given problem using programming languages like C, C++, Java, etc., Coding the
program means translating an algorithm into specific programming language. The
technique of programming using only well-defined control structures is known as
Structured programming. Programmer must follow the language rules, violation of
any rule causes error. These errors must be eliminated before going to the next step.
5. Testing and Debugging
After removal of syntax errors, the program will execute. However, the output of
the program may not be correct. This is because of logical error in the program. A
logical error is a mistake that the programmer made while designing the solution to
a problem. So, the programmer must find and correct logical errors by carefully
examining the program output using Test data. Syntax error and Logical error are
collectively known as Bugs. The process of identifying errors and eliminating them
is known as Debugging. During this phase, there is need to check whether the code
written in the previous step is solving the specified problem or not. That means we
20
test the program whether it is solving the problem for various input data values or
not. We also test whether it is providing the desired output or not.
6. Maintenance
After testing, the software project is almost complete. The structure charts, pseudo-
codes, flowcharts and decision tables developed during the design phase become
documentation for others who are associated with the software project. This phase
ends by writing a manual that provides an overview of the program’s functionality,
tutorials for the beginner, in-depth explanations of major program features,
reference documentation of all program commands and a thorough description of
the error messages generated by the program.
The program is actively used by the users. If there is need for any enhancements,
all the phases are to be repeated to make the enhancements. That means in this
phase, the solution (program) is used by the end-user. The program is deployed
(installed) at the user’s site. Here also, the program is kept under watch till the user
gives a green signal to it. Even after the software is completed, it needs to be
maintained and evaluated regularly. In software maintenance, the programming
team fixes program errors and updates the software.
21
In sequential composition, different program components execute in sequence on
all processors. Based on the number of microprocessors, computers can be
classified into Sequential computers and Parallel computers. Any task complete in
sequential computers is with one microcomputer only. Most of the computers we
see today are sequential computers where in any task is completed sequentially
instruction after instruction from the beginning to the end. The parallel computer
is relatively fast. New types of computers that use a large number of processors.
The processors perform different tasks independently and simultaneously thus
improving the speed of execution of complex programs dramatically. Parallel
computers match the speed of supercomputers at a fraction of the cost.
Sequential program structures are forms in which program components are
constructed, organized, and interrelated. In learning a programming language,
there is a need to learn about two important aspects of the language: its syntax and
semantics. The syntax of a language is the grammatical rules that govern how
words, symbols, expressions, and statements may be formed and combined. The
semantics of a language are the rules that govern its meaning. In the case of
computer language, meaning is defined in terms of what happens when the
program is executed.
The main features of the computer are still visible in the features of the
programming language. These features are storage, input and output, operation of
data, and control.
Storage
Computers require a set of instructions and data to be stored in their memory to
perform a specific task. This stored program concept originated ever since the
invention of Charles Babbage’s difference engine in 1822. In programming
languages, data are identified by name rather than by their location addresses in
main storage. The names that associate stored data values are called identifiers
because an identifier is the name by which the data value may be identified. An
identifier is a constant if it is always associated with the same data value and it is a
variable if its associated data value is allowed to change. Changing a variable’s value
implies changing what is stored.
22
When using names in programs, care must be taken to specify whether the names
are literals or identifiers. When names or letters are used literally, they are called
literals, and they are distinguished from identifiers by placing them within
quotation marks. So, the instruction PRINT “N” means print the letter N, and the
instruction PRINT N means print the value associated with N.
Data Declaration
A variable is a symbolic name assigned to a data item by the programmer. At any
particular time, a variable will stand for one particular data, called the value of a
variable, which may change from time to time during a computing process. The
value of a variable may change many times during the execution of a program. A
variable is usually given a name by the programmer. The variable must be declared
that is to state its data type and its Value.
A data type is a classification of data, which can store a specific type of information.
Data types are primarily used in computer programming in which variables are
created to store data. There are many traditional data types found in most
languages. The act of defining a variable is called data declaration.
Declarations provide information about the name and type of data objects needed
during program execution. Every language supports a set of primitive data types.
Usually, these include integer, real, Boolean, and character or string. A language
standard determines the minimum set of primitive types that the language
compiler must implement. There are two types of declaration, implicit declaration
and explicit declaration. Implicit declarations or default declarations are those
declarations that are done by the compiler when no explicit declaration or user-
defined declaration is mentioned. For example, in 'Perl' the compiler implicitly
understands that:
$abc = 'astring' is a string variable and
$abc = 7; is an integer variable.
In an explicit declaration, the user explicitly defines the variable type. For
example:
Float A, B;
In this example, it specifies that it is of float type variable which has names A & B.
23
Purpose of Declarations:
i. Choice of storage representation: The translator determines the best storage
representation of data types which is why it needs to know primarily the
information of data type and attribute of a data object.
ii. Storage Management: It helps the computer to make the best use of memory
for data object by providing its information so that the computer can allocate
the optimum size of memory for the data.
A variable name does not have an associated value until it has been assigned one.
In computer programming, initialization is the assignment of an initial value for a
data object or variable. How initialization is performed depends on the
programming language, as well as the type, storage class, etc., of an object to be
initialized.
24
9 // Compute area
10 area = radius * radius * 3.14159;
11
12 // Display results
13 System.out.println("The area for the circle of radius " +
14 radius + " is " + area);
15 }
16 }
Variables such as radius and area correspond to memory locations. Every variable
has a name, a type, a size, and a value. Line 3 declares that the radius can store a
double value. The value is not defined until a value is assigned. Line 7 assigns 20
into radius. Similarly, line 4 declares variable area, and line 10 assigns a value into
area. Java uses System.out to refer to the standard output device and System.in to
the standard input device. By default, the output device is the display monitor, and
the input device is the keyboard. To perform console output, you simply use println
method to display a primitive value or a string to the console.
Operations on Data
The operations that may be applied to data items of various types were discussed
in the previous chapter. It remains to examine how these operations are
incorporated into programs. Operations are expressed in the form of statements.
The simplest statement is the assignment statement. It consists of a variable name,
followed by the assignment operator (=), followed by some sort of expression. The
assignment operation has the form:
variable = expression
The assignment operation is used to assign a name to a value. Thus, it is used
whenever there is need to keep track of a value that is needed later. Some typical
uses include:
• initialize a variable (count = 0)
25
• increment/decrement a counter (count = count + 1)
• accumulate values (sum = sum + item)
• capture the result of a computation (y = 3*x + 4)
• swap two values (t = x; x = y; y = t)
The assignment operator is not commute i.e. x = e is not the same as e = x.
Control
In the problem-solving phase of computer programming, you will be designing
algorithms. This means that you will have to be conscious of the strategies you use
to solve problems in order to apply them to programming problems. These
algorithms can be designed though the use of flowcharts or pseudocode. To
implement an algorithm, it should be described in an understandable form. The
descriptions are called constructs. The key to better algorithm design and thus to
programming, lies in properly defining the control structures. These control
structures can be grouped into three constructs namely the sequence structure, the
decision structure or selection structure and the repetition or iteration structure.
The sequence structures
The first type of control structures is called the sequence structure. This structure
is the most elementary structure. The sequence structure is a case where the steps
in an algorithm are constructed in such a way that, no condition step is required.
The sequence structure is the logical equivalent of a straight line.
Example 1: Suppose you are required to design an algorithm for finding the average
of three numbers, and the numbers should be inputted by the user.
follows:
Step1: start
Step2: input num1, num2, num3
Step3: sum = num1+num2+num3
Step4: Average = sum/3
26
Step5: print Average
Step6: stop
Start
Input num1,
num2, num3
Sum = num1+num2+num3
Average = sum/3
Print Average
stop
27
accept number1, number2
sum = number1 + number2
print “The sum is “, sum
product = number1 * number2
print “The Product is “, product
end program
In pseudocode form:
If condition is true
Then do task A
else
Do Task-B
28
In this example, the condition is evaluated, if the condition is true Task-A is
evaluated and if it is false, then Task-B is executed
A variation of the construct of the above figure is shown below
29
The logical operators used in pseudo-codes are
= is equal to
> is greater than
< is less than
>= is greater than or equal
<= is less than or equal
<> is not equal to
Example 4: The following shows how the selection control structure is used in a
program where a user chooses the options for multiplying the numbers, adding, or
subtracting them.
Use variables: choice, of the type character
ans, number1, number2, of type integer
display “choose one of the following”
display “m for multiply”
display “a for add”
display “s for subtract”
accept choice
display “input two numbers you want to use”
accept number1, number2
if choice = m
then ans = number1 * number2
if choice = a
then ans = number1 + number2
if choice = s
then ans = number1 - number2
30
display ans
Compound Logical Operators
There are many occasions when there is a need to extend the conditions that are
to be tested. Often there are conditions to be linked.
In everyday language, there is a statement like ‘If I had the time and the money I
would go on holiday’. The ‘and’ means that both conditions must be true before any
action is taken. Another statement is ‘I am happy to go to the theatre or the cinema’.
The logical link this time is “or”. Conditions in if statements are linked in the same
way. Conditions linked with ‘and’ only result in an action when all conditions are
true.
For example, if a >b and a > c then display “a is the largest”. Conditions linked with
an ‘or’ leads to an action when either or both are true.
Example 5: The program is to input an examination mark and test it for the award
of a grade. The mark is a whole number between 1 and 100. Grades are awarded
according to the following criteria:
>= 80 Distinction
>= 60 Merit
>= 40 Pass
< 40 fail
The pseudo-code is
Use variables: mark of type integer
If mark >= 80 display “distinction”
If mark >= 60 and mark < 80 display “merit”
If mark >= 40 and mark < 60 display “pass”
If mark < 40 display “fail”
An if statement on its own is often not the best way of solving problems. A more
elegant set of conditions can be created by adding an else statement to the if
31
statement. The else statement is used to deal with situations as shown in the
following examples.
Example 6: A person is paid at the top for category 1 work otherwise pay is at the
normal rate.
If the work is category 1
pay-rate is top
Else
pay-rate is normal
The else statement provides a neat way of dealing with alternative conditions. In
pseudo- code this can be written as:
If
work = cat1
then
p-rate: = top
Else
p-rate = normal
33
Then
Display “insurance is medically dependent”
Else
Display “entry invalid”
34
Repetition or Iteration Structure
A third structure causes the certain steps to be repeated.
Example 8: A program segment repeatedly asks for entry of a number in the range
1 to 100 until a valid number is entered.
35
REPEAT
DISPLAY “Enter a number between 1 and 100”
ACCEPT number
UNTIL number < 1 OR number > 100
36
Use variable: number of type real
DISPLAY “Type in a number, or press zero to stop”
ACCEPT number
WHILE number <> 0
Square = number * number
DISPLAY “The square of the number is”, square
ENDWHILE
37
Loop 1
Loop 2
Loop 3
Loop 4
In the example, n is usually referred to as the loop variable, or counting variable, or
index of the loop. The loop variable can be used in any statement of the loop. The
variable should not be assigned a new value within the loop, which may change the
behaviour of the loop.
Example 12: Write a program to calculate the sum and average of a series of
numbers. The pseudocode solution is:
Use variables: n, m, count of the type integer,
Sum, average of the type real
SUM = 0
FOR (n = m, n <= count, n + 1)
SUM = sum + n
ENDFOR
Average = sum / (count-m+1)
DISPLAY “The sum of the numbers is “, sum
38
DISPLAY “Average of the numbers is “, average
Flowcharts have been used in this section to illustrate the nature of the three
control structures. These three are the basic control structures out of which all
programs are built. Beyond this, flowcharts serve the programmer in two distinct
ways: as problem solving tools and as tools for documenting a program.
Example 13
Design an algorithm and the corresponding flowchart for finding the sum of n
numbers.
Pseudocode Program
Step1: start
Step2: initialize sum =0
Step3: input n
Step4: for(i=1,i<=n,i++)
Sum = sum +i
Endfor
Step5: output sum
Step6: stop
In this example, ‘I’ is used to allow counting of the numbers for the addition. ‘I’ is
compared with ‘n’ to check whether the numbers have been exhausted or not in
order to stop the computation of the sum (or to stop the iteration structure). In
such a case,
‘I’ is referred to as a counter.
The corresponding flowchart will be as follows:
39
40