Programmingbasicfor OLevel

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

Computer Science

Teacher: Maruf Ahmed


Programming basics

Algorithm:
- An algorithm is a plan, a logical step-by-step process for solving a problem.
- Algorithms are normally written in pseudocode or drawn as a flowchart.

Pseudocode:
- Pseudocode is a simple method of showing an algorithm.
- It describes what the algorithm does by using English key words that are very similar to those
used in a high-level programming language.
- However, pseudocode is not bound by the strict syntax rules of a programming language. It does
what its name says; it pretends to be programming code!

Flowchart:
- A flowchart shows diagrammatically the steps required to complete a task with some pre-defined
shapes (boxes) and the order that they are to be performed.
- A flowchart consists of specific shapes which are linked together with flow lines.
- It is basically a diagrammatic representation of an algorithm.

Stages of an algorithm:
- Algorithms usually consist of three different stages. They are Input, Process and Output stages.

Input:
- is used to enter data into the system
- to get / receive / read data from a file

Pseudocode example:
Values are input using the INPUT keyword as follows:
INPUT <identifier>
Most of the time the identifier is a variable
INPUT Number
Whatever the value is given by the user the value will be stored in variable Number.
Prompt: Before taking any input it is always recommended to give a message regarding the type of value
the user is expected to give. This type of message is known as input message or more precisely known as
prompt. So the following example is a better way to take input from the user.

Pseudocode example:
OUTPUT “Please enter a number: ”
INPUT Number

Process:
- to manipulate / change data in some way
- to perform a calculation / find a result

Pseudocode example:
MyChar ← 'X' [Storing a CHAR type value in MyChar]
MyNum ← MyNum + 1 [Updating the previous value of MyNum by adding 1 to it]

1
Process is always represented with Left pointing array (←) in pseudocode.
Output:
- to send data out from the system
- to display / print / transmit / show data / write data to a file

Pseudocode example:
OUTPUT "Hello World"
Message can be displayed using OUTPUT keyword
Result of a variable can be output using a message or without a message
For example:
OUTPUT Total [Displayed without any message, it will only show the value that will be held in variable
Total]
OUPUT “The total is: ”, Total [Displayed with a message]

N.B. When you want to display the result of a variable, it must not be in any speech mark.
You have to understand that every OUTPUT keyword will give a new line on screen. Several values,
separated by commas, can be output using the same keyword.
For example, OUTPUT “The total of ”, count, “numbers is: ”, Total

INPUT and OUTPUT statements together


OUPTUT “Please enter your answer: ”
INPUT Answer
OUTPUT “You have given input of ”, Answer

N.B. A comma (,) is used as a separator between variables, and also between a message and a variable.

Arithmetic operators used in pseudocode:


Standard arithmetic operator symbols used are:
+ (plus for addition)
– (hyphen for subtraction)
* (asterisk for multiplication)
/ (forward slash for normal division where the quotient may be in whole number or in decimal)
^ (Caret for raised to the power of)

Examples – arithmetic operations


Answer ← Score * 100 / MaxMark
Answer ← Pi * Radius ^ 2

PEMDAS rule (order of operations):


The order of operations is a rule that tells the correct sequence of steps for evaluating a math expression.
We can remember the order using PEMDAS: Parentheses, Exponents, Multiplication and Division (from
left to right), Addition and Subtraction (from left to right). It is good practice to make the order of
operations in complex expressions explicit by using parentheses.

The integer division operators DIV and MOD can also be used. Both the operators will give the result in
whole numbers only. In both cases the first number is divided by the second number.
DIV: DIV operator is used to get the integer quotient after the division of first number by the second
number
2
X←15 DIV 4
The result of X will be 3, as 4 goes into 15, 3 times as a whole
MOD: MOD operator is used to get the integer remainder after the division of first number by the
second number
X←17 MOD 4
The result of X will be 1 as 4 goes into 17, 4 times as a whole and the integer remainder is 1

Keywords:
- Keywords, also known as reserved words, are a type of predefined tokens in a programming
language that have special meanings and purposes
- These words are reserved by the language and cannot be used as variable names or any other
identifiers
- In pseudocode, keywords have the same use as in any programming language. It is highly
recommended that all the keywords are written in capital letters in pseudocode

Basic constructs needed in developing and algorithm: Algorithms may be expressed using four basic
constructs. They are Assignment, Sequence, Selection and Repetition / Iteration.

Assignment:
- A value is given to a variable
The assignment operator is left pointing arrow (←) in pseudocode
Assignments should be made in the following format:
<identifier> ← <value> or an expression
It means that the value of the right hand side will be assigned to the identifier on the left hand side. It is
never the other way around.
The identifier must refer to a variable or a constant. The value may be any expression that evaluates to a
value of the same data type as the variable.

Pseudocode example:
Counter ← 0
Counter ← Counter + 1
TotalToPay ← NumberOfHours * HourlyRate
Y← “Hello world”
P←P+10
X←10^2
In Computer Science, X ← 10 is correct but 10 ← X is not correct. That means a literal or an expression
can be to the right side of the assignment operator and not to the left side.

Sequence:
- A number of steps are performed, one after another

Pseudocode example:
OUTPUT “ Enter your age: ”
INPUT Age
OUTPUT “Your age is:”, Age
In the above example, statements will be executed in the order that has been written.

3
Selection:
- In a selection statement, the path is decided depending on the result of a condition
- Under certain conditions some steps are performed, otherwise different (or no) steps are
performed.
- Two structures are used for selection. One is IF structure and the other is CASE structure.
IF structure example:
IF A>20
THEN
OUTPUT “The value is greater than 20”
ELSE
OUTPUT “The value is not greater than 20”
ENDIF

CASE structure example:


INPUT Option
CASE OF Option
1 : OUTPUT “Sunday”
2 : OUTPUT “Monday”
OTHERWISE OUTPUT “Wrong choice”
ENDCASE

Repetition/iteration:
- A sequence of steps is performed may be for a number of times or may be for an unknown
number of times.
- For an unknown number of times, a condition is set with the loop structure and it continues
depending on the result of the condition in the loop structure

Three different loop structures are used in pseudocode.


1. FOR....TO....NEXT [known as count-controlled loop]
2. WHILE....DO....ENDWHILE [known as pre-condition loop]
3. REPEAT....UNTIL [known as post-condition loop]

Data type: For each variable you are going to use in the program, the data type for that variable must be
identified. The identifier (name) along with the data type needs to be declared before you use in the
program. You cannot use the same variable for holding two different data type values.
A data type classifies how the data is stored, displayed and the operations that can be performed on the
stored value. For example, a variable with an integer data type is stored and displayed as a whole number
and the value stored can be used in arithmetic calculation. You cannot use this integer variable for storing
any other type of values such as of STRING or REAL data type.

Basic data types used in pseudocode:

Date type Description Example of literal (a representation of


a value)
STRING A sequence of zero to more characters. Delimited by double quotes. A string
No arithmetic operation can be done. may contain zero characters (i.e. the
ASCII value is used internally for each empty string)
character. e.g. "This is a string", "" (empty string)
x ← “Hello World”
4
CHAR A single character. No arithmetic A single character delimited by single
operation can be done. ASCII value is quotes, e.g. ꞌxꞌ, ꞌcꞌ, ꞌ@ꞌ
used internally for the character. x ← „T‟
INTEGER A whole number which can be both Written as normal in the denary system,
positive and negative. Arithmetic e.g. 5, –3
operation can be done. x ← 10
REAL A number capable of containing a Always written with at least one digit on
decimal part as well as a whole number. either side of the decimal point, zeros
This can be both positive and negative. being added if necessary, e.g. 4.7, 0.3,
Arithmetic operation can be done. – 4.0, 1.0
x ← 20.25
BOOLEAN The logical values TRUE or FALSE Either TRUE or FALSE
x ← TRUE

Variable:
- A name given to a memory location that can contain a value and that may change during the
execution of the program.
- A variable can only contain one particular type of data and one value at any one time.
- The same variable cannot be used to store a different data type value in the same program. That
means if a variable has been declared as integer, then it can be used to store only integer
throughout the program and no value of any other data type

Variable declarations are required before they are used in a program.


Declarations are made as follows:
DECLARE <identifier> : <data type>
Example – variable declarations
DECLARE Counter : INTEGER
DECLARE TotalToPay : REAL
DECLARE GameOver : BOOLEAN

If any program requires multiple variables of the same data type to be used, then they can be declared
together separated by comma.

For example:
DECLARE Num1, Num2, Result : INTEGER

Constant:
- A name given to a memory location that can contain one value and that cannot change during the
execution of the program
- A constant can only contain one particular type of data
- There is no way a constant value should be changed during the execution of the program

When we know that the value will not be changed during the execution of the program then we use
constant. Constant cannot be used to take input. It can only be used to assign a literal value before use.

Reason / Advantages of using constant:


- To change a value of the constant, it just needs to change in one place and the change will be
reflected throughout the program.
5
- It makes the code more secured as accidentally the value of constant cannot be changed.

Constants are declared by stating the identifier and assigning the literal value in the following format:
CONSTANT <identifier> ← <value>
Example – CONSTANT declarations
Example of Constant: Use the word Constant before the constant name.
No two constant can be declared together. Each constant must be declared separately.
CONSTANT HourlyRate ← 6.50 [Referring to a REAL data type value]
CONSTANT DefaultText ← "N/A" [Referring to a STRING data type value]
CONSTANT Discount ← 10 [Referring to a INTEGER data type value]

Only literals can be used as the value of a constant. A variable, another constant or an expression must
not be used.

Rules for naming an identifier (names for variables, constants, arrays, subroutines etc.):
 There cannot be any space in any identifier
 Identifiers are in mixed case using Pascal case (PascalCase is a naming convention in which the
first letter of each word in a compound word is capitalized.), e.g. FirstName.
 They can only contain letters (A–Z, a–z) and digits (0–9).
 They must start with a letter and not a digit. Accented letters and other characters, including the
underscore, should not be used. As in programming, it is good practice to use identifier names that
describe the variable, procedure or function to which they refer.
 Keywords should never be used as identifier names. For example INPUT, OUTPUT, IF, FOR etc.
should not be used as identifiers
 Identifiers should be considered case insensitive, for example, Countdown and COUTNDOWN
should not be used as separate variables.

Example of valid variable names: FirstName, Number1 etc.


Example of invalid variable names: First Name, 1Number

Initializing a variable:
This refers to the process wherein a variable is assigned an initial value before it is used in the program.
Without initialization, if a variable is used on the right hand side of the assignment operator then this can
lead to an unpredictable output or crash the program.
For example, Total ← 0 [Here variable Total has been initialized with zero]
Later on in the program this may be used as Total ← Total + Number [The previous Total has been added
to Number to update the new Total]
Another example is:
Count ← 0 [Here variable Count has been initialized with zero]
Count ← Count + 1 [Variable Count has been incremented by 1 later on in the program]
But without initializing Count ← 0, if Count ← Count + 1 statement is used then the program will try to
add a value of Count with 1, but the variable does not have any value assigned to it. So there will be an
error as Count has not been defined.

6
Flowchart symbols used to represent a flowchart

For drawing flowchart as an algorithm, the following shapes are used.

Symbol Name Function


Terminator This shape represents the „Start‟ and „Stop‟/
„End‟ of the process.

Input / Output This shape represents the input or output of


something into or out of the flowchart.

Process This shape represents something being performed


or done.

Decision This shape represents a decision (Yes/No or


True/False) that results in two lines representing
the different possible outcomes.

Flow lines An arrow represents control passing between the


connected shapes.

Subroutine This shape represents a subroutine call that


will relate to a separate, non-linked flowchart

Some basic pseudocode examples

Write down a pseudocode to assign a name in a constant and display it.


Solution:
CONSTANT PersonName ← “Bill Gates”
OUTPUT “The name is ”, PersonName

Write down a pseudocode that will take a name as an input from a user and displays it.
Solution:
DECLARE PersonName: STRING
OUTPUT “Please enter your name: ”
INPUT PersonName
OUTPUT “Your name is ”, PersonName

7
Write down a pseudocode that will add store two whole numbers 20 and 50 in two constants and display
the result.
Solution:
DECLARE Addition : INTEGER
CONSTANT Num1 ← 20
CONSTANT Num2 ← 50
Addition ← Num1 + Num2
OUTPUT “The total of ”, Num1, “and ”, Num2, “is ”, Addition

Write down a pseudocode that will take two numbers as input and display the total.
Solution:
DECLARE Num1, Num2, Result: REAL
OUTPUT “Please enter first number: ”
INPUT Num1
OUTPUT “Please enter second number: ”
INPUT Num2
Result ← Num1 + Num2
OUTPUT “The total of ”, Num1, “and ”, Num2, “is ”, Result

Alternate way (multiple inputs taken together):


DECLARE Num1, Num2, Result: REAL
OUTPUT “Please enter two numbers: ”
INPUT Num1, Num2
Result ← Num1 + Num2
OUTPUT “The total of ”, Num1, “and ”, Num2, “is ”, Result

Write down a pseudocode that will take input of a name of a student and the mark achieved by the
student and displays the name and the mark together with a proper output message.
Solution:
DECLARE SName : STRING
DECLARE Mark : INTEGER
OUTPUT “Please enter the student name: ”
INPUT SName
OUTPUT “Please enter the mark: ”
INPUT Mark
OUTPUT “The name of the student is ”, SName, “and the mark achieved by the student is ”, Mark

You might also like