0% found this document useful (0 votes)
26 views200 pages

c8 Editable Lower Quality

Chapter 8 covers fundamental programming concepts including variables, constants, data types, input/output, and programming structures such as sequencing, selection, and iteration. It emphasizes the importance of data types for effective data processing and provides examples in pseudocode and Python. The chapter also includes practical tasks for calculating volumes of geometric shapes, reinforcing the learned concepts.

Uploaded by

eday2047
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views200 pages

c8 Editable Lower Quality

Chapter 8 covers fundamental programming concepts including variables, constants, data types, input/output, and programming structures such as sequencing, selection, and iteration. It emphasizes the importance of data types for effective data processing and provides examples in pseudocode and Python. The chapter also includes practical tasks for calculating volumes of geometric shapes, reinforcing the learned concepts.

Uploaded by

eday2047
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 200

CHAPTER 8

PROGRAMMIN
G
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Variables and
Constants

Definition:
Both variables and constants are containers for storing a
value. Once created, the variable is stored in a computer
memory and it can be used.

10
refer to the data
Variable is created
stored in the
Computer memory memory by name
Variables VS
Constants

A named data store that contains a value that MAY


CHANGE (vary) during the execution of a program.

Variables Eg. High score of a game

A named data store than contains a value that DOES NOT


CHANGE during the execution of a program.

Constant Eg. Number of days in a week


Pseudocode
Variables and Constants

DECLARE FirstVar : INTEGER


DECLARE SecondVar : INTEGER Variables

CONSTANT FirstConst <- 500


Constant
CONSTANT SecondConst <- 100
Python Code
Variables and Constants

.py

total_price_var = 0
ticket_price_const = 25
Constant
Variables number_of_tickets = input("Enter
number of ticket")
total_price_var = number_of_tickets
* ticket_price_const
*Python does not
require any
separate
declarations and
does not
differentiate
between
constants and
variables
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Basic Data
Types

In order for a computer system to process and store data effectively, different kinds of data
are formally given different TYPES, so that:

"a" in ascii
Data can be stored in
an appropriate way 110000
1 97 in denary

Giving data a "TYPE" helps the computer to differentiate the data


Basic Data
Types

In order for a computer system to process and store data effectively, different kinds of data
are formally given different TYPES, so that:

numbers with mathematical


operators
Eg. 3 + 5 = 8
Data can be
manipulated effectively
characters with concatenation

Eg. "a" + "b"= "ab"


Basic Data
Types

In order for a computer system to process and store data effectively, different kinds of data
are formally given different TYPES, so that:

Auto validation
5 Basic Data
Types
Intege Real/ Char String Boolea
A positive or AFloat
positive or A variable or A variable or A variable or
r
negative whole
number that can
negative number
with a fractional
constant that is
a single
n
constant that is
several
constant that
can have only
be used with part. Real numbers character characters in two values
mathematical can length. Strings TRUE or FALSE.
operators be used with vary in length
mathematical and may even
operators have no
characters
(known as an
empty string)
Exampl
es
Intege Real/ Char Strin Boolea
Float
r g n
25 25.0 'c' "ccc" TRUE
"" FALSE
Test your
understanding!

Intege Rea Char Strin Boolea


r
25 l
25.0 'c' g
"ccc" n
TRUE
What data type
is:
"Footbal
l"
Intege Rea Char Strin Boolea
r
25 l
25.0 'c' g
"ccc" n
TRUE
What data type
is:
"Footbal
l"
Intege Rea Char Strin Boolea
r
25 l
25.0 'c' g
"ccc" n
TRUE
What data type
is:
35.
2
Intege Real Char Strin Boolea
r
25 25.0 'c' g
"ccc" n
TRUE
What data type
is:
35.
2
Intege Real Cha Strin Boolea
r
25 25.0 r
'c' g
"ccc" n
TRUE
What data type
is:
int(10.5
2)
Intege Rea Char Strin Boolean
r
25 l
25.0 'c' g
"ccc" TRUE
What data type
is:
int(10.5
2)
Intege Rea Char Strin Boolea
r
25 l
25.0 'c' g
"ccc" n
TRUE
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Input and
Output
Main function

Take input from a keyboard and output to a screen

Output

Input
Inpu
t Pseudocode
Python Code
INPUT Age
IF Age > 18
THEN
OUTPUT "You are an
adult"
ELSE
OUTPUT "You are a kid"
ENDIF
Inpu Each input needs to
be accompanied by a

t
PROMPT prompt

PROMPT
Pseudocode
Python Code
OUTPUT "What is your age"
INPUT Age
IF Age > 18
THEN
OUTPUT "You are an
adult"
ELSE
OUTPUT "You are a kid"
ENDIF
Input and
Output
Input can also be in the form of file (excel, image). See Chapter 8.3

Output

Input
Inpu
t

All inputs default as strings, so if the input should be an integer or real number, commands
are also used to change the data type of the input (for instance, in Python these are int() or
float()).
Outpu
For a program to be useful, the user needs to know what results
are being output, so each output needs to be accompanied by a
message explaining the result.

t Pseudocode
Python Code
INPUT Age
IF Age > 18
THEN
OUTPUT "You are an
adult"
ELSE
OUTPUT "You are a kid"
ENDIF
Output
PROGRAMMING TIME
TASK
SPECIFICATION
So far we have learned the following topics:
• Variables and Constant
• Basic Data Type
• Input and Output
Let's put everything that we have learned into practice.
TASK 1
VOLUME OF A SPHERE
To calculate the volume of a sphere, we can use the
formula:

Your task is to create a program that asks the user for


the radius of a sphere, and then calculate its volume.
The program must output a message showing the result
calculated.

TIPS:
You need to create a constant called PI that has the
value of 3.142. You can perform multiplication in
python using the * symbol. A fraction can be created
using the division / symbol (eg. 4/3).
TASK 2
VOLUME OF A CYLINDER
To calculate the volume of a cylinder, we can use the
formula:

Your task is to create a program that asks the user for


the radius and height of a cylinder, and then calculate
its volume. The program must output a message
showing the result calculated.

TIPS:
You need to create a constant called PI that has the
value of 3.142. You can perform multiplication in
python using the * symbol.
ANSWER (TASK 1)
ANSWER (TASK 2)
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Sub Chapter Outline
8.1.4.1 Sequencing

8.1.4.2 Selection

8.1.4 8.1.4.3 Iteration


Programming
Fundamentals Totalling and
8.1.4.4
Counting

String handling
8.1.4.5

Arithmetic, Logical and


8.1.4.6 Boolean Operators
Sequencing

The ordering of the steps in an algorithm is very important. An


incorrect order can lead to incorrect results and/or extra steps that are
not required by the task.

Step 1: Ask for a radius

Step 2:Using the


radius,calculate the volume
Sequencing

The ordering of the steps in an algorithm is very important. An


incorrect order can lead to incorrect results and/or extra steps that are
not required by the task.

Eg. The process of frying an egg

Step 1: Heat up the pan


Step 2: Pour in oil
Step 3: Crack the egg and add the egg
into the pan
Step 4: Eat
Sequencing

You can't do this...

Eg. The process of frying an egg

Step 1: Crack the egg and add the egg


into the pan
Step 2: Heat up the pan
Step 3: Pour in oil
Step 4: Eat
Sequencing

The ordering of the steps in an algorithm is very important. An


incorrect order can lead to incorrect results and/or extra steps that are
not required by the task.

Step 1: Ask for radius

Step 2: Ask for height

Step 3:Using the radius and


height,calculate the volume
Sequencing

Human would recognise that this is wrong, but


THE COMPUTER WOULD JUST DO AS IT IS TOLD

Step 1:Using the radius and


height,calculate the volume

Step 2: Ask for radius

Step 3: Ask for height


Sub Chapter Outline
8.1.4.1 Sequencing

8.1.4.2 Selection

8.1.4 8.1.4.3 Iteration


Programming
Fundamentals Totalling and
8.1.4.4
Counting

String handling
8.1.4.5

Arithmetic, Logical and


8.1.4.6 Boolean Operators
Selection

Another fundamental construct in programming is the ability for the


code to make a decision or ask a question, usually when there are
several possible options.

Show football
Yes
Do you like videos

football?

Show other
No
videos
Selection

Selection can be written in programs by using either an


IF statement ...

Pseudocode
Python Code
INPUT Age
IF Age > 18
THEN
OUTPUT "You are an If
statement
adult"
ELSE
OUTPUT "You are a kid"
ENDIF
Selection

or a CASE statement.

Java Code
Pseudocode

INPUT Grade
CASE OF Grade
A : OUTPUT "Excellent"
B : OUTPUT "Not bad huh"
C : OUTPUT "Fair"
D : OUTPUT "Work harder"
OTHERWISE : OUTPUT "Invalid input"
ENDCASE
Selection

Python does not have a CASE statement. Alternatively, the statement


"elif" (stands for else-if) is used.

Pseudocode Python Code

INPUT Grade
CASE OF Grade
A : OUTPUT "Excellent"
B : OUTPUT "Not bad huh"
C : OUTPUT "Fair"
D : OUTPUT "Work harder"
OTHERWISE : OUTPUT "Invalid input"
ENDCASE
PROGRAMMING TIME -
SELECTION
TASK 1 - ODD OR EVEN
Ask the user for a number. Determine if the number
entered is an odd number or an even number. Print out
the result.

Tips:
When we divide a number by 2, an odd number will
have a remainder of 1 and an even number will have a
remainder of 0.

You can check the remainder of a number by using the


"%" symbol. Eg.

5%2 will give you 1.


TASK 2 - VOWEL OR
CONSONANT
Ask the user for a character. Determine if the character
entered is a vowel (a, e, i, o, u). If so, print out the
vowel character. Otherwise, print "this character is a
consonant".

Tips:
A simple if-else statement is not enough!
ANSWER (TASK 1)
ANSWER (TASK 2)
Sub Chapter Outline
8.1.4.1 Sequencing

8.1.4.2 Selection

8.1.4 8.1.4.3 Iteration


Programming
Fundamentals Totalling and
8.1.4.4
Counting

String handling
8.1.4.5

Arithmetic, Logical and


8.1.4.6 Boolean Operators
Iteration

Iteration takes place in algorithm when the rules determine that a step
or steps should be repeated until a condition is met or until told to
stop.

Eg. The algorithm for frying 5 eggs


Step 1: Heat up the pan
Step 2: Pour in oil
Step 3: Crack the egg and add the egg into the pan
Step 4:Put the fried egg on a plate
REPEAT Step 3 and 4 until for 5 times.
Iteration

Another word for iteration is loop. There are 3 different types of loop in
iterative programming.

Count-controlled Pre-condition Post-condition


loop loop loop

For a set Always has at


May have no least one
number of iterations
iterations iteration
Iteration

Another word for iteration is loop. There are 3 different types of loop in
iterative programming.

Count-controlled Pre-condition Post-condition


loop loop loop

For a set Always has at


May have no least one
number of iterations
iterations iteration
Count-controlled
loop

THE NUMBER OF LOOPS OR ITERATIONS IS ALREADY DECIDED. A COUNTER IS


USED TO RECORD HOW MANY TIMES THE ITERATION HAS OCCURRED. THIS
TYPE OF LOOP IS KNOWN AS A FOR LOOP.

FOR Counter <- 1 TO 10


OUTPUT Counter
NEXT Pseudocode that
output value
from 1 to 10
PSEUDOCODE SYNTAX
BREAKDOW
Initial value of the
Counter variable
N

FOR Counter <- 1 TO 10


OUTPUT Counter When the Counter
variable reaches this
Increment the NEXT
value, the loop will
existing Counter
terminate
value by 1
(eg. 3 -> 4,
7 -> 8
, etc)
PYTHON CODE SYNTAX
BREAKDOW
Variable that is used as a
counter
N
range function

Steps incremented to
the counter variable
at each iteration
Notes: You don't have
for keyword to specify step if the
value is 1.

Starting value of the


When the counter
counter variable
variable reaches this
value, the loop will
end
PYTHON CODE

OUTPUT

RUN THIS CODE

Notes: "10" is not printed as the loop


has already terminated.
PYTHON CODE

OUTPUT

RUN THIS CODE

step = 2
Count-controlled
loop

Comparing pseudocode with Python code

FOR Counter <- 1 TO 10


OUTPUT Counter
NEXT
Iteration

Another word for iteration is loop. There are 3 different types of loop in
iterative programming.

Count-controlled Pre-condition Post-condition


loop loop loop

For a set Always has at


May have no least one
number of iterations
iterations iteration
Pre-condition
loop

This is where a condition must be true before the loop or operation takes place.
This type of loop is known as a while loop.

Total ← 0
OUTPUT "Enter value for mark, -1 to finish "
INPUT Mark
WHILE Mark <> -1 DO
Total ← Total + Mark
OUTPUT "Enter value for mark, -1 to finish"
INPUT Mark
ENDWHILE
Pre-condition This is where a condition must be true before the loop or operation
loop (Pseudocode) takes place.

SYNTAX
Condition that must be
met before the BREAKDOW
indented codes can be
run N
Total ← 0
OUTPUT "Enter value for mark, -1 to finish "
INPUT Mark
WHILE Mark <> -1 DO

Total ← Total + Mark


indented codes
OUTPUT "Enter value for mark, -1 to finish"
INPUT Mark
ENDWHILE
Pre-condition
Condition that must SYNTAX
loop (Python Code)
be met for indented
BREAKDOW
N
chunk of code to run

The above program will keep adding what the user enters until user keys in
the value "-1". The total will be printed.
Iteration

Another word for iteration is loop. There are 3 different types of loop in
iterative programming.

Count-controlled Pre-condition Post-condition


loop loop loop

For a set Always has at


May have no least one
number of iterations
iterations iteration
Post-condition
loop

This is where a condition must be true after the loop or operation takes place. It
can be implemented using the REPEAT ... UNTIL loop in Pseudocode.

Total ← 0
Mark ← 0
REPEAT
Total ← Total + Mark
OUTPUT "Enter value for mark, -1 to
finish "
INPUT Mark
UNTIL Mark = -1
Post-condition This is where a condition must be true after the loop or
loop (Pseudocode) operation takes place.

SYNTAX
BREAKDOW
N
Total ← 0
Mark ← 0
REPEAT
Total ← Total + Mark Indented code. It will
OUTPUT "Enter value for mark, -1 to run at least once.

finish "
INPUT Mark Condition that must be
UNTIL Mark = -1 met for the indented
codes to repeat
This is where a condition must be true after the loop or
Post-condition
operation takes place.
loop (Java Code)

SYNTAX
*DO ... WHILE loop in Java
BREAKDOW
N

Indented code. It will


run at least once.

*Python only
supports pre-
condition and
Condition that must be met for count-controlled
the indented codes to repeat loop
PROGRAMMING
TIME

ITERATION
TASK 1 - MULTIPLES OF 3
Use a FOR loop (count-controlled) to output the first 5 multiples of 3. Your program should
output the following:
TASK 2-
COUNTDOWN
Use a FOR loop (count-controlled) to output a countdown from 10 to 0. Your program should
output as the diagram below:
TASK 3-
COUNTDOWN (WHILE
LOOP)
Use a WHILE loop (count-controlled) to output a countdown from 10 to 0. Your program
should output as the diagram below:
TASK 4-
I WANT POSITIVE NUMBER
Write a program that asks user to input numbers REPEATEDLY until the user keys in a
positive number.

Your program would work like this:


TASK 5-
SUM TO N
Write a program that asks user to input numbers REPEATEDLY until the user keys in a
positive number (from Task 4). Using the positive number (N), calculate the sum from 0 up
to N.

Eg. If the user enters the value "5", your program should output the value 15 (5 + 4 + 3 + 2
+ 1 + 0 = 15).

Test case:

INPUT = 3, OUTPUT = 6
INPUT = 10, OUTPUT = 55
INPUT = 100, OUTPUT = 5050
ANSWER - TASK 1
ANSWER - TASK 2
ANSWER - TASK 3
ANSWER - TASK 4
ANSWER - TASK 5
Sub Chapter Outline
8.1.4.1 Sequencing

8.1.4.2 Selection

8.1.4 8.1.4.3 Iteration


Programming
Fundamentals Totalling and
8.1.4.4
Counting

String handling
8.1.4.5

Arithmetic, Logical and


8.1.4.6 Boolean Operators
Totalling

Totalling is used to add one number to an existing


stored number, usually contained in two different
variables.

Eg. Python code to "Total" up the sum from 0 to 10


(0 + 1 + 2 ... 10).
Counting

Counting keeps a check on how many iterations a


program has performed in a loop.
Sub Chapter Outline
8.1.4.1 Sequencing

8.1.4.2 Selection

8.1.4 8.1.4.3 Iteration


Programming
Fundamentals Totalling and
8.1.4.4
Counting

String handling
8.1.4.5

Arithmetic, Logical and


8.1.4.6 Boolean Operators
"abcdefghijk"
lower

upper
length
substring
Find the number of characters in a
"abcdefghijk" string.

Pseudocode Python code

length value ← LENGTH("abcdefghijk")


OUTPUT value

#The value "11" will be output.

*Both text in quote and a variable in data type string can be


used.
Extracting part of a string
"abcdefghijk"

0 1 2 3 4 5 6 7 8 9 10
substring
a b c d e f g h I j k
*In Python, index starts at 0.
(one character)
Extracting part of a string
"abcdefghijk"

0 1 2 3 4 5 6 7 8 9 10
substring
a b c d e f g h I j k
*In Python, index starts at 0.
(range of *syntax variable[x:y], x is the starting position and
y is the ending
characters)
Extracting part of a string
"abcdefghijk"

1 2 3 4 5 6 7 8 9 10 1
substring
a b c d e f g h I j k1
*In Pseudocode, index starts at 1.
(range of
characters) text <- "abcdefghijk"
shorten_text <- SUBSTRING(text, 1,
3)

OUTPUT shorten_text # "abc"


Convert all the letters in a string to
"abcdefghijk" uppercase

upper

text <- "abcdefghijk"


upper_text <- UCASE(text)

OUTPUT upper_text
# "ABCDEFGHIJK"
# "ABCDEFGHIJK"
Convert all the letters in a string to
"abcdefghijk" lowercase

lower

text <- "ABCDEFGHIJK"


lower_text <- LCASE(text)

OUTPUT lower_text # "abcdefghijk"

# "abcdefghijk"
Sub Chapter Outline
8.1.4.1 Sequencing

8.1.4.2 Selection

8.1.4 8.1.4.3 Iteration


Programming
Fundamentals Totalling and
8.1.4.4
Counting

String handling
8.1.4.5

Arithmetic, Logical and


8.1.4.6 Boolean Operators
Arithmetic
Operators

Action Pseudocode Python

Add + +

Subtract - -

Multiply * *

Divide / /
Raise to the power
of ^ **
Remainder
division MOD %
Integer
division DIV //
Arithmetic
Operators

Quick try out (on Python):


• Find the value of 352 + 102 + 21
• Find 2 to the power of 11
• Find the remainder when 1980 is
divided by 7
• Try to add two characters/strings
and see what you observed
Logical
Operators

Operator Pseudocode Python

More than > >

Less than < <

Equal = ==
Greater than
or equal to >= >=
Less than or
equal to
<= <=

Not Equal <> !=


Boolean
Operator

Operator Description Pseudocode Python

AND Both True AND and

OR Either True OR or

NOT Not True NOT not


PROGRAMMING
TIME

OPERATORS
TASK 1 - USING
OPERATORS
Takes 2 numbers as inputs from the user (N1 and N2):

Compare N1 and N2:

• Output with a suitable message if both numbers are not equal


• Output with a suitable message identifying which number is larger
• Output with a suitable message identifying which number is smaller
• Output with a suitable message if both numbers are equal
TASK 1B - USING
OPERATORS
[Continued] Take in a 3th number (N3).

• Output with a suitable message if all three numbers are not equal
• Output with a suitable message if all numbers are equal.
ANSWER - TASK 1
ANSWER - TASK 1B
Sub Chapter Outline
8.1.4.1 Sequencing

8.1.4.2 Selection

8.1.4 8.1.4.3 Iteration


Programming
Fundamentals Totalling and
8.1.4.4
Counting

String handling
8.1.4.5

Arithmetic, Logical and


8.1.4.6 Boolean Operators
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Sometimes, it is necessary to execute one IF
Nested statement, followed by another, and then
Selection followed by another. This is when nested
selection is needed.

Nested IF-statement
Normal IF-statement
Nested SYNTAX
Selection BREAKDOW
N
Nested IF-statement

An IF
statement
An IF within an
IF
statement statement
Nested SYNTAX
Selection BREAKDOW
N
What does the code below do?

Check if number input is more


than 50.
If so, check again if it is more
than 75.
In the same way as a selection can be nested, a
Nested loop can be nested inside another loop.
Iteration

Normal Loop Nested Loop


Nested STEP-BY-
Iteration STEP
Output
Normal Loop >> "Counter = 1"
>> "Counter = 2"
>>

Program ended as the


loop ends when counter
= 3. Easy!!
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

Output
>>
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

Output
>> Counter = 1
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

Output
>> Counter = 1
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

Output
>> Counter = 1
>> Another counter = 1
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

*return to inner loop


Output
>> Counter = 1
>> Another counter = 1
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

Output
>> Counter = 1
>> Another counter = 1
>> Another counter = 2
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

*inner loop ended, return to outerloop


Output
>> Counter = 1
>> Another counter = 1
>> Another counter = 2
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

Output
>> Counter =1
>> Another counter = 1
>> Another counter = 2
>> Counter =2
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

Output
>> Counter =1
>> Another counter = 1
>> Another counter = 2
>> Counter =2
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

Output
>> Counter =1
>> Another counter = 1
>> Another counter = 2
>> Counter =2
>> Another counter = 1
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

Output
>> Counter =1
>> Another counter = 1
>> Another counter = 2
>> Counter =2
>> Another counter = 1
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

Output
>> Counter =1
>> Another counter =1
>> Another counter =2
>> Counter =2
>> Another counter =1
>> Another counter =2
Nested STEP-BY-
Iteration STEP
Code
for counter in range(1,3):
print("Counter = " + str(counter))
for another_counter in range(1,3):
print("Another counter = " + str(another_counter))

*outer loop ends, program ends, final output


Output
>> Counter =1
>> Another counter =1
>> Another counter =2
>> Counter =2
>> Another counter =1
>> Another counter =2
PROGRAMMING
TIME

NESTED
STATEMENTS
TASK 1 - MULTIPLICATION
TABLE
Write a nested for loop program to print multiplication table in Python. Your
program should produce the following output.
(Tips: Not an easy problem).
TASK 2 - STARS
Use a nested loop to print the following pattern in Python.

Tips: Harder to do than Task 1.


ANSWER - TASK 1
ANSWER - TASK 2
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Subroutine

When writing an algorithm, there are often similar tasks to perform that make use of the
same groups of statements. Instead of repeating these statements and writing new
code every time they are required, many programming languages make use of
subroutines, also known as named procedures or functions.

These are defined once and can be called many times within a program.
Subroutine

For example, let's say you have a program that


would do the following operations to an input
number:

- Add 5
- Multiply by 3
- Divide by 2
- Add 100
- Minus 20
- Then, print the total.

You program might look like this.


Subroutine

For example, let's say you have a program that


would do the following operations to two input
number:

- Add 5
- Multiply by 3
- Divide by 2
- Add 100
- Minus 20
- Then, print the total.

You program might look like this.


SIMILAR!

SIMILAR!
We can group this
chunk of code
together and make a
procedure/function
We can group this
chunk of code
together and make a
procedure/function
And use the function
like
this
SYNTAX
BREAKDOWN function name, parameter, the value which we
def keyword used to call the function insert into the function
Procedure vs Function

A subroutine that will A subroutine that will


not return a value return a value
Procedure vs Function
does not return a value
return a value

number is returned here


Parameter vs No
Parameters
parameter
Global and local variables
Global and local variables

local variable, only can be


used within the function
Can be
used here
because
they are global variable,can
global be used anywhere
variables

cannot be
used here
PROGRAMMING
TIME

FUNCTIONS
TASK 1 - STARS
Write a function that can print one line of stars (*********).
In your codes, call the function 5 times to print 5 lines of stars. Your
program should output the following:
TASK 1B - STARS
EXTENDED
Create a function that takes in a "number" parameter. Using the number(N)
parameter, print N lines of stars. For instance:

user input = 6
user input = 3
TASK 2 - FAHRENHEIT TO
CELCIUS
The formula to convert Fahrenheit to Celsius is

Celsius = (Fahrenheit - 32) * (5/9)

Write a function that converts Fahrenheit to Celsius.

Your function will need to take in a value as parameter and return the
result.

Then, use the function to calculate two input values from the user.
ANSWER - TASK 1
ANSWER - TASK 1B
ANSWER - TASK 2
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Library Routine

A "physical" library contains books


Library Routine

The library of a programming language


stores library routines which are small blocks
of pre-written code (functions) that can be
called easily and repeatedly.
Library Routine

They are perfectly programmed routines that


can be called upon at any time with no pre-
programming required and are designed to
handle some of the most common problems
when writing any software.
Library Routine
Some common libraries that we use in this subjects:

Short for modulo, Short for division,


used to divide 2
MOD
used to find a
remainder of a DIV numbers
division

Return the output of Return a randomly


the nearest integer selected integer

ROUND to a floating point


number that is
RANDO from a given range
of integers
passed to it
M
Library Routine
CO
MOD
DE
Pseudocode

MOD(10,3)
Try it
out in
Value = 10%3
Python

DIV DIV(10,3) Value = 10//3

ROUND ROUND(6.933,2) Value = round(6.97354, 2)

from random import random


RANDOM RANDOM() Value = random()
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Maintainable
Program

Once a program is written, it may need to be


maintained or updated by another programmer at a
later date. The programmer may have no
documentation other than a copy of the source
program. Even a programmer looking at their own
program several years later may have forgotten
exactly how all the tasks in it were completed!
Maintainable 3 ways to write a maintainable
Program program

• Always use meaningful identifier names for variables, constant, arrays,


procedures, functions.

Instead of:

Do this:
Maintainable 3 ways to write a maintainable
Program program

2. Program should be divided into modules using procedures and functions


whenever possible

Instead of:

Do this:
Maintainable 3 ways to write a maintainable
Program program

3. Be fully commented using your programming language’s commenting feature.


*comments will not be run by computer, only as indicators to programmers

Instead of:

Do this:
Maintainable Fun fact: A book has been
Program written to"teach" programmers
how to write maintainable code.

464 pages!!!
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
One-dimensional
array RECA
P
Variables are memory locations that can store a
piece of data.

10
refer to the data
Variable is created
stored in the
Computer memory memory by name
One-dimensional
array ARRA
Y
An array is a series of these memory locations,
where all of the data is of the same data type.

2 3 4
refer to the
Variable is created
GROUP OF data
Computer memory
stored in the
memory by name
One-dimensional
array ARRA
Y
Each location can still store 1 data, but locations
can be grouped together.

2 3 4
refer to the
Variable is created
GROUP OF data
Computer memory
stored in the
memory by name
One-dimensional
array ARRA
Y
Index
0 1 2
Data
2 3 4
Most programming languages automatically set
the first index of an array to ZERO.
One-dimensional
array ARRA
Index
0 1 2
Y
Data
2 3 4
To retrieve an element of an array, we would just
do:

ARRAYNAME[index]
One-dimensional
array ARRA
Declare an array in Pseudocode
Y
DECLARE MyList:ARRAY[0:2] OF 0 1 2
INTEGER
One-dimensional
array ARRA
Y
Each position in the array can be populated in an array by defining the value
at each index position

MyList[2] = 20
0 1 2
One-dimensional
array ARRA
Y
In Python, arrays are created using the LIST functionality.

0 1 2
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Two-dimensional A two-dimensional array has multiple columns
array and multiple rows of data, all with the same data
type.Very much like an excel file.

Inde 0 1 2
x
0 2 3 4
1 5 6 7
2 8 9 10
Two-dimensional Example usage:
array A world map in a simple 2D game.

Inde 0 1 2
x G - ground
0 T T G T - tree
Z -zombies
1 Z G G H - humans

2 H G G
Two-dimensional Example usage:
array Students mark in different subjects

Physics Chemistry Biology

Inde 0 1 2
x
StudentA 0 76 65 67
StudentB 1 32 90 75
StudentC 2 66 77 31
Two-dimensional
array PSEUDOCOD
E
Inde 0 1
DECLARE MyList:ARRAY[0:2,0:1] OF x
INTEGER 0

1
TYPE 2

RO COLUMN
Two-dimensional
array PSEUDOCOD
E
Inde 0 1
MYLIST[2,1] <- 10 x
0

2 10
Two-dimensional
array PSEUDOCOD
E
Inde 0 1
OUTPUT MYLIST[0,0] x
0 30
#30 will be OUTPUT
1

2 10
Two-dimensional
array PYTHON
Inde 0 1
x
0 30 20
1 15 5
A two-dimensional array in 2 0 10
Python is basically a list
inside a list!
Two-dimensional
array PYTHON
In Python, you can loop through a list like this.
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>>
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>>
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>>
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>> a
>>
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>> a
>>
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>> a
>> b
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>> a
>> b
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>> a
>> b
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>> a
>> b
>> c
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>> a
>> b
>> c
Two-dimensional STEP-BY-
array STEP
Loop through a list of list in python

Code
big_list = [["a", "b"], ["c", "d"]]

for small_list in big_list:


for character in small_list:
print(character)

>> a
>> b
>> c
>> d
PROGRAMMING
TIME

ARRAYS
TASK 1 - SQUARE
Turn every item in the following list into squares. You can print out your
result.
TASK 2 - EXAM MARKS
Create a list of list in python to represent the
data. Then, find out:
• Find out the top marks for Physics, Physics Chemistry Biology

Chemistry and Biology. Inde 0 1 2


• The student with the highest average x
mark
StudentA 0 76 65 67
StudentB 1 32 90 75
Tips: The index and subject/name column is StudentC 2 66 77 31
for illustration only, you do not need to
include them in your list. Your list should be
a 3x3 two dimensional list.
ANSWER - TASK 1
ANSWER TASK
2
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Reading and We have seen programming involves the
writing input of a lot of data.

Pseudocode
Python Code
INPUT Age
IF Age > 18
THEN
OUTPUT "You are an
adult"
ELSE
OUTPUT "You are a kid"
ENDIF
Reading and
writing

Input can also be in the form of file.


Reading and
writing

Files can be read and written to.


Reading from a
file
Read
mode

Output:
Chapter Outline

8.2.1 One-dimensional
8.1.1 Variables and Constants
Arrays
8.1.2 Basic Data Types 8.2.2 Two-dimensional
8.1.3 Input and Output Arrays
8.1.4 Programming Fundamentals
8.1.5 Nested Statements
8.1.6 Procedures, Functions and
8.3.1 Reading from a
Parameters
file
8.1.7 Library Routines
8.3.2 Writing to a file
8.1.8 Creating a Maintainable Program
Writing to a file

Create a file if it does not exist

Write
mode

Write each string in the content into the


newly created txt file +
a new line
Writing to a file

Output
Code

You might also like