0% found this document useful (0 votes)
2 views

Pseudocode Notes

The document provides an overview of programming concepts including input/output, variable declaration, data types, constants, arithmetic operations, order of precedence, string handling, comments, sequence, selection, iteration, arrays, and subroutines. It explains how to use these concepts in pseudocode and Python, illustrating with examples for clarity. Additionally, it covers the importance of subroutines for code organization and reusability.

Uploaded by

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

Pseudocode Notes

The document provides an overview of programming concepts including input/output, variable declaration, data types, constants, arithmetic operations, order of precedence, string handling, comments, sequence, selection, iteration, arrays, and subroutines. It explains how to use these concepts in pseudocode and Python, illustrating with examples for clarity. Additionally, it covers the importance of subroutines for code organization and reusability.

Uploaded by

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

PseudoCode & Python Code:

1. Display
Output refers to the process of displaying or saving the results of a program to the use
OUTPUT Welcome to Grade 10

2. Getting input from user


• Input refers to the process of providing data or information to a program.
• 'User Input' is data or information entered by the user during program execution.
OUTPUT Enter A value
INPUT A

3. Variable declaration
• Data Types - A data type is a classification of data into groups according to the kind of data they
represent. Computers use different data types to represent different types of data in a program
The basic data types include:
• Integer: used to represent whole numbers, either positive or negative Examples:10, -5, 0
• Real: used to represent numbers with a fractional part, either positive or negative Examples:
3.14, -2.5, 0.0
• Char: used to represent a single character such as a letter, digit or symbol Examples: 'a', 'B', '5', '$'
• String: used to represent a sequence of characters Examples: "Hello World","1234","@#$%
• Boolean: used to represent true or false values Examples: True, False

DECLARE a : INTEGER
DECLARE b : STRING
DECLARE c : REAL
a<-10
b<-Nithya
c<-2.56
Illegal variable declaration:
2myvar = "John"
my-var = "John"
my var = "John"
4. CONSTANT
• Variables & Constants Variables and constants are used to store a single item of data in a
program.
• This can be accessed through the identifier. Variables can be changed during program execution
while constants remain the same.
DECLARE Pi : Real
CONSTANT Pi<- 3.145
5. Arithematic operator
OUTPUT Enter a, b value
INPUT a,b
add<-a+b
sub<- a-b
mul<-a*b
div<-a/b
mod<-a%b
pow<-a^b
6. Order of precedence:
X<-(5-3)*12/6+1
OUTPUT X

7. String & Integer are different


a=”6”
b=”5”
print(a+b) //65
7.String handling functions
1.Concatenation
firstname ← "Nidhyathi”
surname ← "thi "
fullname ← firstname + " " + surname
OUTPUT fullname
2. Length
word ← "Nidhyathi"
OUTPUT LENGTH(word)
Word=”Nidhyathi”
Print(len(word))

3. Substring extract a word from string


OUTPUT(word,3,6) #o/p dhya
print(word[2:5]) #o/p dhy
4.lower case
LCASE(word)
Print(word.lower())
5. Upper case
UCASE(word)
Print(word.upper())
8. Comment
Single line comment - #
#declare variable a
Multiple line comment – “”” “””
“”” This is calculation of area of circle
Get value for radius
Find the area using power method”””
9. Sequence
• Sequence is a concept that involves executing instructions in a particular order
• Itis used in programming languages to perform tasks in a step-by-step manner
• Sequence is a fundamental concept in computer science and is used in many programming
languages
Mark1<-90
Mark2<-90
Total<-Mark1+Mark2
Average<- Mark1+Mark2/2
Grade<-A

10. Selection (check condition)


• Selection is a programming concept that allows you to execute different sets of instructions based
on certain conditions.
• There are three main types of selection statements:
1. IF ELSE statements
2. CASE statements/ Elif statement
3. Nested If statements
• Operators
Comparison Meaning Pseudocode Result Notes
operators example

= Equal to 5=5 True Many


languages
use a double
==

<> Not 5 <> 5 False Many


equal to languages
use !=

> Greater 5>5 False


than

>= Greater 5 >= 5 True


than or
equal to

< Less than 5<5 False


<= Less than 5 <= 5 True
or equal •
to •

• Comparision operator

Operator Description

AND Returns TRUE if both conditions are TRUE

Returns TRUE if either of the conditions are


OR TRUE

A TRUE expression becomes FALSE and vice


NOT versa

• If else statements are used to execute one set of statements if a condition is true and a different set
of statements if the condition is false.
IF average >= 60
THEN
OUTPUT "Pass"
ELSE
OUTPUT "Fail"
ENDIF

CASE statements will branch depending on many different possible values for an identifier
CASE OF number
1: OUTPUT "Monday"
2: OUTPUT "Tuesday"
3: OUTPUT “Wednesday”
4: OUTPUT “Thursday”
5: OUTPUT “Friday”
6: OUTPUT “Saturday”
7: OUTPUT “Sunday”
OTHERWISE OUTPUT "Invalid number"
END CASE
case 5:
print "Friday";
case 6:
print "Saturday";
case 7:
print "Sunday";
case _:
print "Invalid number";
• If else if statements are used to test multiple conditions and execute different statements for each
condition.
x←5
IF x > 0
THEN
OUTPUT "x is positive"
ELSE IF x < 0
THEN
OUTPUT “x is negative”
ELSE
OUTPUT “x is 0”
ENDIF
x=5
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
elif x%2==0:
print(“X is an even”)
elif x%2!=0:
print(“X is an odd”)
else:
print("x is 0")

Nested If:
• Nested selection is an if statement inside an if statement
• If the first if statement is true, it will run the if statement which is nested inside
• Otherwise, it will skip to the "else if" or"else" which is part of that if statement.
IF average >= 60
THEN
IF attendance>=60
THEN
OUTPUT "Pass"
ELSE
OUTPUT “Fail”
ELSE
OUTPUT "Fail"
ENDIF
If average>=60:
If attendance>=60:
print(“pass”)
else:
print(“fail”)
else:
print(“fail”)

11. Iteration - keywords (looping, times, repeating, Iteration)


• Iteration is the process of repeating a set of instructions until a specific condition is met.
• It is an important programming concept and is used to automate repetitive tasks.
• There are three main types of iteration:
▪ Count-controlled loops ( for)
▪ Precondition loops (while)
▪ Post condition loops (repeat untill/do… while)
▪ Nested for loop
Count-controlled Loops
▪ A count-controlled loop is used when the number of iterations is known beforehand It is also known
as a definite loop
▪ It uses a counter variable that is incremented or decremented after each iteration
▪ The loop continues until the counter reaches a specific value
#print even
FOR Even ← 2 TO 10 STEP 2
OUTPUT Even
NEXT Even
#print odd
FOR Odd <- 1 To 9 STEP 2
OUTPUT Odd
NEXT Odd
#printvalues 10-0
FOR Count ← 10 TO 0 STEP -1
OUTPUT Count
NEXT Count
for even in range(2, 10,2):
print(even)
for odd in range(1,9,2):
print(odd)
for values in range(10, 0,-1):
print(values)
for name in range(1,5,1):
print(“Charan”)
Pre-condition Loops
▪ A precondition loop is used when the number of iterations is not known beforehand and is
dependent on a condition being true Itis also known as an indefinite loop
▪ The loop will continue to execute while the condition is true and will stop once the condition
becomes false
OUTPUT "Please enter password: "
INPUT Password
WHILE Password <> "charan"
OUTPUT "Invalid password – try again"
INPUT Password
ENDWHILE
OUTPUT "Correct password"
password = input("Enter password: ")
while password!=”nithya”:
print("Invalid password try again")
password = input("Enter password: ")

Postcondition Loops
▪ A post-condition loop is used when the loop must execute atleast once, even if the condition is false
from the start
▪ The condition is checked at the end of the loop
REPEAT
INPUT guess
UNTIL guess = 42
Post condition loops don’t exist in Python and would need to be restructured to a precondition loop
Nested Iteration
Nested iteration refers to a loop inside another loop.
FOR i ← 1 TO 10
FOR j ← 1 TO 5
OUTPUT "i = ", i, " j = ", j
END FOR j
END FOR i
for i in range(1, 11):
for j in range(1, 6):
print("i = ", i, " j = ", j)

# outer loop
for i in range(1, 5):
# inner loop
for j in range(1, 6):
print("*", end=" ")
print('')
* * * * *

* * * * *

* * * * *

* * * * *

12.Totalling
• Totalling involves adding up values, often in a loop
• A total variable can be initialised to 0 and then updated within a loop, such as:
total ← 0
FOR i ← 1 TO 10
INPUT num
total ← total + num
NEXT i
OUTPUT total
total = 0 #add is 0 mult is 1
for i in range(1, 11):
num = int(input("Enter a number: "))
total += num #total=total+num
print("Total:", total)
1. Sum of even numbers – 2+4+6+8+10=
2. Sum of odd numbers – 1+3+5+7+9=
13. Counting
• Counting involves keeping track of the number of times a particular event occurs
• A count variable can be initialised to 0 and then updated within a loop, such as:
count ← 0
FOR i ← 1 TO 10
INPUT num
IF num > 5
THEN
count ← count + 1
END IF
NEXT i
OUTPUT count
count = 0
for i in range(1, 11):
num = int(input("Enter a number: "))
if num > 5:
count += 1 #count=count+1
print("Count:", count)
14. Array – Python(List)
• An array is a data structure that allows you to hold many items of data which is referenced by one
identifier
• All items of data in the array must be of the same data type
• An array of 10 strings called UserNames could be
declared as:
DECLARE Usernames : ARRAY[1:10] OF STRING
usernames = ["psmith ", " ltorvalds ", " pwatts ",” sjones”]
Insert values to an array:
Usernames[1] ← "psmith"
Usernames[2] ← "ltorvalds"
Usernames[3] ← "pwatts"
Usernames[4] ← "sjones"
Usernames[5] ← "mpatel"
Usernames[6] ← "bwright"
Usernames[7] ← "mgreen"
Usernames[8] ← "dthomas"
Usernames[9] ← "nwhite"
Usernames[10] ← "fdavies"
First element of the array: Usernames[1]
Last element of the array: Usernames[LENGTH(Usernames)]
First element of the array: Usernames[0]
Last element of the array: Usernames[len(usernames)-1]
cars = ["Ford", "Volvo", "BMW"]
cars[0] = "Toyota"
print(cars)
Length of an array:
LENGTH(Usernames)
Print(len(usernames))
Print an array:
FOR i ← 1 TO LENGTH(Usernames)
OUTPUT Username[i]
NEXT i
for x in usernames:
print(x)
Linear searching an array
DECLARE username: ARRAY[1:4] OF STRING
Username[1]<- “anu”
Username[2]<- “bala”
Username[3]<- “ravi”
Username[4]<- “nithya”
Username[5]<- “sai”
OUTPUT "Type search key: " #ravi
INPUT Search
FOR i ← 1 TO LENGTH(Usernames)
IF Usernames[i] = Search
THEN
OUTPUT "Name found"
ENDIF
NEXT i
cars = [12, 34, 54]
print(cars)
x=int(input(“enter car number”))#54
for i in range(len(cars)):
if cars[i] == x:
print("Name found in position",i)

DECLARE Price: ARRAY[1:5] OF REAL


DECLARE Quantity: ARRAY[1:5] OF INTEGER
Price[1] 0.99
Price[2] 1.28
Price[3] 3.69
Price[4] 0.49
Price[5] 8.29
Quantity[1] 2
Quantity [2] 3
Quantity [3] 1
Quantity [4] 4
Quantity [5] 1
Totalprice 0.0
DECLARE TotalPrice : REAL
FOR i ← 1 TO LENGTH(Price)
DECLARE Subtotal : REAL
Subtotal  Price[i] * Quantity[i]
TotalPrice  TotalPrice + Subtotal
NEXT i
OUTPUT "Total price: ", TotalPrice

price=[0.99,1.28,3.69,0.49,8.29]
quantity=[2,3,1,4,1]
totalprice=0.0
subtotal=0.0
for i in range(len(price)):
subtotal=price[i]*quantity[i]
totalprice=totalprice+subtotal
print(totalprice)

2 dimensional Array:
Find and display the total mark for each student:
Student1 12 14 8 7 17
Student2 6 8 5 3 13
Student3 16 15 9 10 18

FOR s ← 1 TO 3
StudentTotal ← 0
FOR m ← 1 TO 5
StudentTotal ← StudentTotal + Mark[s][m]
NEXT m
OUTPUT StudentTotal
NEXT s
marks=[[12,14,8,7,17],[6,8,5,3,13],[16,15,9,10,18]]
for i in range(0,3):
Studenttotal = 0
for j in range(0,5):
Studenttotal=Studenttotal+marks[i][j]
print(" Student",i+1,"Total = ",Studenttotal,"\n")
Print student total
Complete the following with the words beneath
_________ allow many data items to be stored under one _________. Each item in the array can be
accessed by its array _________. Indexes start at _________. By using a _________ we can easily loop
through an array. Arrays have a _________ and all items in the array have the same _________.
arrays data type identifier zero or one
index FOR loop fixed length
15. Subroutines
• Subroutines are often used to simplify a program by breaking it into smaller, more manageable
parts.
Advantages of subroutines:
• Avoid duplicating code and can be reused throughout a program,
• Improve the readability and maintainability of code,
• Perform calculations,to retrieve data, or to make decisions based on input.
Parameters are values that are passed into a subroutine.
Types of parameters:
Be passed by value or by reference.
• When a parameter is passed by value, a copy of the parameter is made and used within the
subroutine.
• When a parameter is passed by reference, the original parameter is used within the subroutine, and
any changes made to the parameter will be reflected outside of the subroutine
• Subroutines can have multiple parameters
Types of subroutines:
1. Procedures
2. Functions
Procedures are defined using the PROCEDURE keyword in pseudocode, def keyword in Python,
Procedures can be called from other parts of the program using their name
1.
PROCEDURE calculate_area(length: INTEGER, width: INTEGER)
area ← length * width
OUTPUT "The area is " + area
END PROCEDURE
calculate_area(5,3)

2.
PROCEDURE showMenu
OUTPUT " Menu "
OUTPUT "=================="
OUTPUT "1: Play game"
OUTPUT "2: Show key controls"
OUTPUT "3: High scores"
OUTPUT "4: Return to main menu"
OUTPUT "5: Exit game"
ENDPROCEDURE
CALL showMenu

1.
def calculate_area(length, width):
area = length * width
print("The area is ", area)

calculate_area(5,3)
2.
def showmenu():
print( " Menu ")
print( "==================")
print( "1: Play game")
print( "2: Show key controls")
print( "3: High scores")
print( "4: Return to main menu")
print( "5: Exit game")
showmenu()

Difference between procedures & functions:


• Both functions and procedures are subroutines
• Values can be passed to both procedures and functions
• Functions will return a value after processing has taken place
• Build in procedures - print("Hello“)
• Build in functions - input("Type in your name: ")
Functions:
• Functions are defined using the FUNCTION keyword in pseudocode, def keyword in Python, return a
value using the RETURN keyword in pseudocode, return statement in Python
• Functions can be called from other parts of the program using their name, and their return value
can be stored in a variable
FUNCTION calculate_area(length: INTEGER, width: INTEGER)
area ← length * width
RETURN area
END PROCEDURE
OUTPUT(calculate_area(5,3))
2.
FUNCTION sum(a, b)
total ← a + b
RETURN total
ENDFUNCTION
answer ← sum(5, 3)
OUTPUT answer
def calculate_area(length, width):
area = length * width
return area

print(calculate_area(5,3))
2.
def sum(a,b):
total=a+b #total is a local variable
return total
print(sum(10,20))
Two types of subroutine used in programming:
Functions and procedures
How many parameters can functions and procedures have?
Zero, one or many
Explain the difference between a local and global variables
Globals are accessible anywhere in the program – locals only within the subroutine in which they were
created
What are three reasons that you should try to use subroutines where possible?
Reuse code, decomposition, more maintainable code

17. Python global variables are those which are not defined inside any function and have global scope.

• Python local variables are those which are defined inside a function and their scope is limited to
that function only.
18. Library Routines
• Library routines are pre-written code that can be used in programs to perform specific tasks.
• Using library routines saves time by not having to write code from scratch Library routines are also
tested and proven to work, so errors are less likely
• Some commonly used library routines include:
1. Input/output routines
2. Maths routines
Maths routines
MOD: a function that returns the x MOD y x%y
remainder when one number is
divided by another number

DIV: a function that returns the x DIV y x // y


quotient when one number is
divided by another number

ROUND: a function that rounds a ROUND(x, n) round(x, n)


number to a specified number of print(round(2.34565,3))
decimal places 2.346

RANDOM: a function that RANDOM(x,n) random.randint(x,n)


generates a random number import random
between x and n print(random.randint(1,100))

Routine Example Output


Maximum Print(max([5,2,8])) 8

Minimum min([5,2,8]) 2

Sum sum([5,2,8]) 15

(Mean) average import statistics 5


statistics.mean([5,2,8])
statistics.median([5,2,8])
statistics.mode([5,2,8])

Sort an array animals = ['rabbit', 'cat', 'dog', 'hamster'] ['cat', 'dog',


animals.sort() 'hamster', 'rabbit']

Search an array 'hamster' in animals True


19. Maintaining Programs
Why is it important to create a maintainable program?
Improve program quality: A maintainable program is easier to understand and modify, which leads to
fewer bugs and better program quality
Reduce development time and costs: A maintainable program requires less time and effort to modify,
which reduces development time and costs
Enables collaboration: A maintainable program makes it easier for multiple developers to work together
on the same project, as it's easier to understand and modify
Increase program lifespan: A maintainable program is more likely to be updated and maintained
overtime, which increases its lifespan and usefulness
Adapt to changing requirements: A maintainable program is easier to modify to adapt to changing
requirements or new features
How do you create a well maintained program?
Use meaningful identifiers:
• Identifiers are names given to variables, constants, arrays, procedures and functions
• Use descriptive and meaningful identifiers to make your code easier to understand and maintain
• Avoid using single letters or abbreviations that may not be clear to others
Use the commenting feature provided by the programming language:
• Comments are used to add descriptions to the code that help readers understand what the code is
doing
• Use comments to explain the purpose of variables, constants, procedures,functions and any other
parts of the code that may not be immediately clear
• Use comments to document any assumptions or limitations of the code
Use procedures and functions:
• Procedures and functions are reusable blocks of code that perform specific tasks
• Using procedures and functions allows you to modularise your code and make it easier to
understand, debug and maintain
• Procedures and functions should have descriptive names that clearly indicate what they do
Relevant and appropriate commenting of syntax:
• Commenting of syntax is used to explain the purpose of individual lines or blocks of code within the
program
• Use commenting of syntax to describe complex algorithms, or to provide additional information on
the purpose or behaviour of code
File Handling:
• File handling is the use of programming techniques to work with information stored in text files
• Examples of file handing techniques are:
opening text files
reading text files
writing text files
closing text files

• Using files every file is identified by its filename.


• In this section, we are going to look at how to read and write a line of text or a single item of data to
a file.
DECLARE TextLine : STRING // variables are declared as normal
DECLARE MyFile : STRING //file name
MyFile ← "MyText.txt" // writing the line of text to the file
OPEN MyFile FOR WRITE // opens file for writing
OUTPUT "Please enter a line of text"
INPUT TextLine
WRITEFILE, TextLine // writes a line of text to the file
CLOSEFILE(MyFile) // closes the file // reading the line of text from the file
OUTPUT "The file contains this line of text:"
OPEN MyFile FOR READ // opens file for reading
READFILE, TextLine // reads a line of text from the file
OUTPUT TextLine
CLOSEFILE(MyFile) // closes the file
# writing to and reading a line of text from a file
Myfile = open ("Mytext.txt","w") #open file in write mode
TextLine = input("Please enter a line of text ")
Myfile.write(TextLine)
Myfile.close() #close file
print("The file contains this line of text")
Myfile = open ("MyText.txt","r")#open file in read mode
TextLine = Myfile.read()
print(TextLine)
Myfile.close()#close file

You might also like