Chapter 08
PROGRAMMING
What is p rog rammin g ?
• A computer program is a sequence of instructions
written using a Computer Programming Language to
perform a specified task by the computer.
How Do we store data?
VARIABLE CONSTANT
• A named memory location that can • A named memory location
store data. The data can change that can store data. The data
whilst a program is running. cannot change whilst a
program is running.
EXAMPLE USING PYTHON
Number ← 10 #variable( integer data_type)
Colour ← “Red” #variable(String data_type)
Price ← 22.2 #constant(Real data_type)
Print( ‘Total price=‘, price * Number)
D ATA B E I N G S T O R E D I N M E M O RY S PA C E :
0 10 identifier Number 10
1 Red Colour Red
2 22.2 Price 22.2
3 3
4 4
5 5
6 6
IDENTIFIER
A name given to a variable, constant , data structure (e.g. array) or subroutine so that we can use
the data stored in it can be used later inside the code.
Example:
Identifier Number = 10 Value
Assignment
Assignment: A type of programming statement that stores data in a variable and constant.
Rules for IDENTIFIERS
• Names can not start with a numbers.
• There can be no spaces in the name, instead, underscore( _ ) can be
used.
• Can not use the symbols:
!@#$%^&*():”?><,.~`
• Using lower case letters is encouraged.
• Keywords can not be used as the identifier of variable or constant. For
example: int, type, str, list etc.
8.2 DATA TYPE
The characteristics of a piece of data.
The common data types are: String, integer, real and Boolean.
Storing different data types
Storing a string in a variable:
Name ← ‘Asif’
Storing an integer in a constant:
CONSTANT Class ← 9
Storing a real number in a variable:
Height ← 5.25
Storing a Boolean in a variable:
Flag ← TRUE
CONVERTING BETWEEN DATA TYPES
Casting: Converting data from one data type to another data type.
Example : Number ← int(“123”) #converting a string to an integer
Value ←String(22.4) # converting a number to an string
Conversion using Python
number = int(“123”)
value = str(22.4)
8.3 INPUT AND OUTPUT
INPUT OUTPUT
• The user entering data into the program, usually from a • Data that is displayed to the user usually on-screen.
keyboard.
• Used to give information to user.
• Used to take information from user.
• Example :
• Example:
Name ← “Alex”
INPUT Name
OUTPUT (“Hello”, Name)
OUTPUT (“Hello”, Name)
Using python:
Using python:
name = “Alex”
name= input("Enter your name")
print(‘Hello', name)
print(‘Hello', name)
Concatenation
Concatenation: Joining two or more strings together.
8.4 ARITHMETIC OPERATORS
• A symbol that performs mathematical function, i.e, ‘+’ adds two values.
Number1 ← 10
Number2 ← 5
Result1 ← Number1 + Number2
Result2 ← Number1 - Number2
Result3 ← Number1 * Number2
Result4 ← Number1 / Number2
Result5 ← DIV(33 , 7)
Result6 ← MOD(33 , 7)
MOD AND DIV
MOD : Remainder division .
The remainder is returned after the division is
performed.
Example: MOD(135,5) = 0
DIV: Integer division.
The quotient is returned and remainder is
ignored after the division is performed.
Example: DIV(135,5) = 27
Assignment
Addition operation
Subtraction operation
multiplication operation
division operation
DIV operation
MOD operation
OUTPUT
PARENTHESES
• Brackets in a mathematical statement that determines which calculations are
performed first.
• Calculations within the brackets are done first.
• Example: Total ← 1+(2*3)
Total ← (1+2)*3
The first line will result in 7 : (2*3=6; 6+1=7)
The second line will result in 9 : (1+2=3 ; 3*3 = 9)
How to construct a program?
There are three types of constructs within a program.
Sequence Selection Iteration
Count controlled
IF Statement, loop
Pre-Conditioned
CASE Statement loop
Post-Conditioned
loop
8.5 SEQUENCE
• A sequence is series of statements that are
executed( run) once, in the order they are
written.
• It is the first of the three constructs within a
program.
Example:
OUTPUT( “Enter your favorite color”)
INPUT Colour
OUTPUT( “Enter your name”)
INPUT name
OUTPUT(name, “ your favorite color is” ,
Colour)
8.6 SELECTION
Selection is the second In programming, there are
programming construct occasions when a decision
where a section of code is needs to be made. Selection
run only if a condition is is the process of making a
met. decision.
There are two forms of
The result of the decision selection:
determines which part of the • IF statements
program will be executed • CASE statements
next.
IF S TAT E M E N T S
The command IF is followed by a condition that is created using the logic operators. There are three stages of IF statements : IF
, ELSE and ELSEIF . Example:
INPUT NUM1
INPUT NUM2
What can be the relation between NUM1 and NUM2 ?
IF NUM1 > NUM2
OUTPUT ( NUM1 is greater than NUM2)
NUM1 > NUM2
OR ELSE IF NUM1 < NUM2
NUM1 < NUM2 OUTPUT ( NUM1 is smaller than NUM2)
OR
NUM1 = NUM2 ELSE NUM1 = NUM2
OUTPUT ( NUM1 is equal to NUM2)
STRUCTURE OF IF STATEMENT
IF has one comparison and the code inside IF
will only run if that condition is true. If it’s not
true then the code will not run.
It follows the structure :
IF comparison THEN
statement that run if the comparison is true
END IF
EXAMPLE
← 10
1. Num1
IF Num1 =10
THEN
OUTPUT(‘true’)
ENDIF
2. INPUT value_input
stored_value ← 100
IF value_input > stored_value
OUTPUT(‘ it is more than
100)
ENDIF
STRUCTURE OF IF..ELSE STATEMENT
This is added within an IF statement. If the IF
statement’s condition is false then the EISE
will run.
An IF statement can have only one ELSE
statement in it.
EISE follows the structure :
IF comparison THEN
Statements that run if the comparison is true
ELSE
Statements that run if the comparison is false
END IF
1. Num1 ← 10
IF Num1 =10 then
OUTPUT(‘True’)
ELSE
OUTPUT(‘False’)
ENDIF
2. Input Value_input
Stored_value ← 100
IF Value_input > Stored_value
output(‘ It is more than 100’)
ELSE
output(‘ It is less than 100’)
ENDIF
S T R U C T U R E O F I F. . E L S E I F S TAT E M E N T
ELSEIF allows for a second condition to be
used within the same IF Statement so that if the
first condition is False then the second condition
can be checked.
ELSEIF follows the structure:
IF comparison1 THEN
Statements that run if the comparison is true
ELSEIF comparison2 THEN
Statements that run if comparison1 is false and
comparison2 is true
ENDIF
EXAMPLE: Take a number as input from user and check if it is greater,
smaller or equal to the stored number
INPUT Value_input
Stored_value ← 100
IF Value_input > Stored_value
Output(‘ it is more than 100)
ELSEIF Value_input < Stored_value
Output(‘ it is less than 100’)
ELSE
Output(‘They are equal’)
ENDIF
F L O W C H A RT O F I F S TAT E M E N T S
Example : Write pseudocode
Take three numbers as input and find the maximum number.
Ans:
INPUT a
INPUT b
INPUT c
IF a > b AND a> c THEN
OUTPUT(a , “ is maximum”)
ELSEIF b> c
OUTPUT(b , “ is maximum”)
ELSE
OUTPUT(c , “ is maximum”)
ENDIF
SELECT CASE
• A SELECT CASE statement allows the program to take one variable or value, and then have lots of different
options depending what it is equal to.
• A case can have as many CASE statements as needed, but can only ever have a maximum of one default(this runs
if none of the comparisons is true) statement.
CASE follows the structure:
CASE OF variable
value1:
Statements that run if the CASE value1 is true
value2:
Statements that run if the CASE value1 is false, valeu2 is true.
Otherwise
Statements that run if none of the comparisons are true.
ENDCASE
Flowchart of CASE statement
B O O L E A N O P E R ATO R
• A symbol that joins multiple logical comparisons .
• There are three Boolean operators that can be used to join
conditions:
• AND operator
• Returns True when both inputs are true
• NOT operator
• Returns True if the input is false, and returns False if it’s true
• OR operator
• Returns True when one or both inputs are true
EXAMPLE: FINDING THE HIGHEST NUMBER
OUTPUT(‘ Enter 3 numbers:’)
INPUT Number1
INPUT Number2
INPUT Number3
IF Number1 > Number2 AND Number1 > Number3
OUTPUT (‘Number1 is the highest
number’)
ELSEIF Number2 > Number3
OUTPUT (‘Number2 is the highest
number’)
ELSE
OUTPUT (‘Number3 is the highest number’)
ENDIF
8.7 ITERATION
Iteration or loop is a programming
construct where code is run multiple
times- either a finite number of
times, until a condition is true, or Count- controlled loop For…next loop
while a condition is true.
There are three types of loops: Pre- condition loop While…endwhile loop
Post- condition loop Repeat…until loop
COUNT CONTROLLED LOOP
• A type of iteration where code is run a finite
number of times using a counter.
• The loop will run from the start value to the
end value of the counter.
• Most common count controlled loop is FOR loop.
The structure of the FOR loop:
FOR variable ← start value to end value
Code that runs repeatedly
NEXT variable
EXAMPLE USING PYTHON
OUTPUT THE NUMBERS 1 TO 10
OUTPUT THE NUMBERS 1 TO 10 FOR X ← 1 TO 10
OUTPUT (X)
NEXT X
EXAMPLE
Write a pseudocode to find the total of this series Count-
Controlled Loop :
1+2+3+4+……………20.
Ans:
i← 0
Total ← 0
FOR i ← 1 to 20
Total ← sum + i
NEXT i
OUTPUT Total
Example: Write a pseudocode
Take numbers as input and find positive and negative numbers
using Count-Controlled Loop.
ANS:
i← 0
FOR i ← 1 to 10
INPUT a
IF a >= 0
OUTPUT( a, “is Positive”)
ELSE
OUTPUT( a, “is Negative”)
ENDIF
NEXT i
Take 10 numbers as input and find odd and even numbers using
count-controlled loop.
ANS:
i← 0
FOR i ← 1 to 10
INPUT a
IF a MOD 2 = 0
OUTPUT (a, “ is even”)
ELSE
OUTPUT (a, “ is odd”)
ENDIF
NEXT i
PRE-CONDITIONED LOOP
A type of iteration where the condition is checked
before running any code in the loop and the code is
run only if the condition is true.
A WHILE LOOP is a pre-conditioned loop.
A While loop follows the structure:
WHILE condition DO
code that will run if the condition is true
ENDWHILE
EXAMPLE: Outputting the numbers 1 to 10
• Number ← 1
WHILE Number < 11
OUTPUT(Number)
Number ← Number + 1
ENDWHILE
EXAMPLE
Write a pseudocode to find the total of this series using Pre-
Conditioned Loop:
1+2+3+4+……………20.
Ans:
i← 0
Total ← 0
WHILE i <=20
Total ← Total + i
i←i+1
ENDWHILE
OUTPUT Total
Take 10 numbers as input and find odd and even
numbers using Pre-Conditioned Loop.
Take numbers as input and find positive and negative
numbers using Pre-Conditioned Loop.
POST-CONDITIONED
LOOP
• A type of iteration where condition is
checked after the code in the loop is run,
therefore the code always runs once.
• The code is run if the condition is false
and runs until the condition becomes
true.
• A REPEAT UNTIL loop is a post condition loop
and it follows the structure:
REPEAT
code that runs inside the loop
UNTIL Condition
EXAMPLE
Write a pseudocode to find the total of this series using Post-Conditioned
loop:
1+2+3+4+……………20.
Ans:
i← 0
Total ← 0
REPEAT i <=20
Total ← Total + I
i←i+1
UNTIL i >= 20
OUTPUT Total
Take 10 numbers as input and find odd and even
numbers using Post-Conditioned Loop.
Take numbers as input and find positive and
negative numbers using Post-Conditioned Loop.
COUNT CONTROLLED/ PRE-CONDITION / POST CONDITION
LOOP
8 . 8 TO TA L L I N G
A type of program that adds up multiple value to find the
total.
How to write a program that finds total?
Initialize the total to 0
Add the values together ( either initially or within loop)
Example: asking the user to enter 10 numbers and totaling
them:
Total ← 0
FOR Counter ← 0 to 10
OUTPUT(‘Enter a number: ‘)
Total ← Total + input
NEXT Counter
OUTPUT(“ the total is “ & Total)
8.9 COUNTING
A type of program that adds one for every item to find
out how many items there are.
How to write a program that counts:
Initialize a counter variable to 0.
Increment (add 1 to) the counter each time an item is
entered or found.
Example: count how many numbers are there (1 to 100)
that are more than 57.
Count ← 0
FOR X ← 1 to 100
IF X > 50
Count ← Count +1
ENDIF
NEXT X
OUTPUT ( Count )
8.10 String manipulation
What is a string ?
• A string is a piece of text. This could be made up of characters, numbers or
symbols.
How to identify a string ?
• Any characters, numbers or symbols that are found within a double or single
quotation mark can be identified as a string. For example: “ Hello” , ‘123’,
“as@hhj”.
What is string manipulation?
• String manipulation basically refers to the process of handling and analyzing
strings. It involves various operations concerned with modification and
parsing of strings to use and change its data.
There are a lot of different string
manipulators we can use to alter strings,
find values etc. Three of them are :
1. Length: this command will
return the number of characters
are there in a string.
It has the structure:
LENGTH(string)
Example using python:
name= “Asif”
Print(len(name))
2. Substring: this command will return some
of the characters of a string. It has the
structure:
SUBSTRING(string, start character, number
of characters)
Example:
SUBSTRING(“Hello”, 0,1)
using python:
Substring = “Hello”[0:1]
Print(Substring)
Ending
Starting char
char
3. Upper and Lower: the characters(A-Z
and a-z) of a string can be converted from
upper case to lower case and vice-versa.
It follows the structure:
UPPER( string )
LOWER( string )
Example:
Using UPPER with a string :
UPPER(“Hello”)
Using LOWER with a string :
LOWER(“Hello”)
Using UPPER with a string stored in variable:
Word ← “hello”
Word ← UPPER( “hello”)
8 . 1 1 N E S T E D S T A T E M E N T S
A nested statement is one or more selection/iteration
statements inside another selection/iteration statement.
How can this happen?
An IF
A loop inside An IF
statement A loop within a
an IF statement statement in a
inside an IF loop
, or loop ,or
statement , or
Example1: Count how many numbers are more
than 10, and how many are equal to 10
MoreThan10 ← 0
Equalto10 ← 0
For X ← 0 to 5
OUTPUT(“Enter a number”)
INPUT Number
IF Number > 10
MoreThan10 ← MoreThan10 +1
ELSEIF Number = 10
Equalto10 ← Equalto10 +1
ENDIF
NEXT X
this code has an IF statement nested inside a count-
controlled loop.
Examp le2: Ou tp u t o n ly th e vo wels in a
messag e inp u t if th e u ser selects o ptio n 1
OUTPUT (“Enter 1 or 2” )
INPUT Choice
IF choice = 1 THEN
OUTPUT(“Enter a word”)
INPUT Word
FOR Count ← 0 to LENGTH(Word)
Character ← SUBSTRING(Word,
Count,1)
IF Character = “a” OR Character = “e”
OR Character = “i” OR Character = “o”
OR Character = “u”
OUTPUT(Character)
ENDIF
NEXT COUNT
END IF
This has a for loop inside an IF followed by another IF inside the
for loop.
8.12 SUBROUTINES
A subroutine is a self-contained piece of
code that has an identifier(name) and using
that identifier(name) it can be called from
anywhere in the main program.
For example, A code that multiplies two
numbers can be stored in an identifier and
we can call that identifier to do the task of
multiplication instead of doing the entire
multiplication again.
Therefore, subroutines are useful because
they reduce code.
There are two types of
subroutines:
1. Procedure: A procedure
runs the code inside it and
does not return a value to
the program that called it.
The structure of a procedure is:
PROCEDURE identifier()
code to run inside the function
ENDPROCEDURE
2. FUNCTION
Function name
A procedure runs the code
inside it and returns a value
using the Return command to
the program that calls it. Returning product
as value
The structure of a procedure is:
FUNCTION identifier()
code to run inside the function
RETURN value
ENDFUNCTION
Returning value
Scope: The scope of a variable is the areas within a program where the variable can be accessed.
There are two scopes: global and local
Global scope Local scope
• The variable or constant can be accessed • The variable or constant can only be
from any part of the program. accessed in the part of the code where it is
• It includes the main program and any written.
subroutines. • if it is declared first in a subroutine then it
• In most language, it is declared at the top of can only be accessed by the subroutine
the program. • if it is declared in the main program then it
can only be accessed in the main program.
A addition performed using both global and local variable
Global variable Parameter : a value
Parameter that is sent from the
main program to
the subroutine
Subroutine (procedure or
Local variable function).
Main program
8.13 Library routines
A pre-written subroutines that can be called from within the program.
For example, MOD and DIV (slide10) are library functions in some language.
Two of many other library functions are :
1. Round : this will take a real number ( decimal ) and limit how many numbers are there after the
decimal point.
• For example, ROUND( 10.123, 1) will take the number and only leave 1 number after the
decimal point
2. Random : this will generate a random number between two numbers that it takes as parameter.
• For example, ROUND(10,20) will return a number between 10 and 20.
Here, “x” is an
identifier but it does
not indicate that it
stores the total of
two numbers.
Instead of “x”,
“total” is used as an
identifier and it
indicates that it
stores the total of
two numbers.
tes
Here, “#” indica
lls
a comment and te
to
the program not
execute the text
after the symbol
How an identifier can store multiple data of same datatypes?
0 1 2 3 4
• The above shown is an Array called colours .
• This array has 5 spaces that can be traced using their respected index numbers.
• Index is the number of space in an array.
• The best way to visualize is with a table:
index 0 1 2 3 4
Data “red” "green" "blue" "yellow" "black"
• An array can have one dimension, two dimensions, three dimensions, four dimensions, and so on.
1-dimensional array
• An 1-dimensional array has just one row of data.
• For example, Numbers = [10, 5, 90, 26, 87]
• Visualization using table:
index 0 1 2 3 4
Data 10 5 90 26 87
• This array has 5 spaces. The first data item is in position 0 and the data value is 10.
• Array use brackets after the identifier to indicate the index we want to access. For example , Array[0] is accessing the first
element in the array named Array.
• In array named Numbers,
Numbers[0] = 10
Numbers[1] = 5
Numbers[2] = 90
Numbers[3] = 26
Numbers[4] = 87
2-dimensional array
• A 2-dimensional array has two indices.
• The data elements in two dimensional arrays can be accessed using two indices. One index referring to the main or parent
array and another index referring to the position of the data element in the inner array.
• Consider the example of recording temperatures 4 times a day, daily. Such data for 4 days can be presented as a two
dimensional array as below:
Data visualization using table:
Day 1 - 11 12 5 2 index 0 1 2 3
Day 2 - 15 6 10 4 0 11 12 5 2
Day 3 - 10 8 12 5 Day 1 15 6 10 4
Day 4 - 12 15 8 6 2 10 8 12 5
3 12 15 8 6
temperature
The above data can
0 1be 2represented
3 as a two dimensional array as below:
0 1 2 3
Temperature = [[11, 12, 5, 2], [15, 6,10 , 4], [10, 8, 12, 5], [12,15,8,6]]