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

Algorithmic Thinking with Python - Module 2

A structured learning resource designed to align with KTU’s S1 syllabus for Computer Science. This document covers algorithmic problem-solving techniques using Python, including flow control, functions, recursion, and basic data structures. It emphasizes logical thinking, efficient coding practices, and real-world applications, making it an ideal companion for students pursuing foundational computer science studies.

Uploaded by

aadhikassim
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Algorithmic Thinking with Python - Module 2

A structured learning resource designed to align with KTU’s S1 syllabus for Computer Science. This document covers algorithmic problem-solving techniques using Python, including flow control, functions, recursion, and basic data structures. It emphasizes logical thinking, efficient coding practices, and real-world applications, making it an ideal companion for students pursuing foundational computer science studies.

Uploaded by

aadhikassim
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

MODULE -2

ALGORITHM AND PSEUDOCODE REPRESENTATION:-

Meaning and Definition of Pseudocode, Reasons for using pseudocode, The main constructs of pseudocode
- Sequencing, selection (if-else structure, case structure) and repetition(for, while, repeat-until loops), Sample
problems.

FLOWCHARTS :-

Symbols used in creating a Flowchart - start and end, arithmetic calculations, input/output operation, decision
(selection), module name (call), for loop (Hexagon), flow-lines, on-page connector, off-page connector.

ALGORITHM

An algorithm describes a systematic way of solving a problem. It is a step-by- step procedure that produces
an output when given the necessary inputs. An algorithm uses pure English phrases or sentences to describe
the solution to a problem.

PSEUDOCODE

A Pseudocode is a high-level representation of an algorithm that uses a mixture of natural language and
programming language-like syntax. It is more structured than an algorithm in that it uses mathematical
expressions with English phrases to capture the essence of a solution concisely.

Aspect Algorithm Pseudocode


Definition A step-by-step procedure for solving a A human-readable representation of
problem. an algorithm.
Purpose Describes what needs to be done. Provides a way to outline the logic
without syntax.
Language Language-independent, often expressed in natural
Similar to programming languages but
language or formal structures. less strict.
Complexity Can be complex and detailed. Generally simpler and more abstract.
Syntax May have specific syntax rules if in a formal
No strict syntax; focuses on
language. readability.
Execution Not executable; serves as a plan for problem-
Not directly executable but can be
solving. easily translated into code.
Example

Sum of two numbers 1. Start START


2. Get two numbers, A and B INPUT A, B
3. Add A and B to get the sum SUM = A + B
PRINT SUM
4. Print the sum
END
5. End

UCEST105- AlGORITHMIC THINKING WITH PYTHON 1 Prepared By Asst.Prof.Bini Charles, TIST


Ex :01 - write an algorithm and a pseudocode to evaluate an expression, d = a+b∗c.

Evaluate-Algo Evaluate-Pseudo

1. Start Start
2. Read the values of a, b and c. Read(a, b, c)
3. Find the product of b and c. d=a+b∗c
4. Store the product in a temporary variable temp. Print(d)
5. Find the sum of a and temp. Stop
6. Store the sum in d.
7. Print the value of d.
8. Stop.

Ex :02 - write an algorithm and a pseudocode to evaluate Expression d=a/(b+c)

Evaluate-Algo Evaluate-Pseudo

1. Start START
2. Read the values of a, b, and c. READ(a, b, c)
3. Find the sum of b and c and store it in a temporary temp = b + c
variable temp. d = a / temp
4. Divide a by temp. PRINT(d)
5. Store the result in d. STOP
6. Print the value of d.
7. Stop.

Ex :02 - write an algorithm and a pseudocode to find the area of a circle

Evaluate-Algo Evaluate-Pseudo

1. Start START
2. Read the radius rr. READ(r)
3. Calculate the area using the formula Area=PI*r^2 Area = PI * r * r
4. Print the area. PRINT(Area)
5. Stop. STOP

Why pseudocodes?

1. Ease of understanding: Since the pseudocode is programming language independent, novice


developers can also understand it very easily.
2. Focus on logic: A pseudocode allows you to focus on the algorithm’s logic without bothering
about the syntax of a specific programming language.
3. More legible: Combining programming constructs with English phrases makes pseudocode
more legible and conveys the logic precisely.
4. Consistent: As the constructs used in pseudocode are standardized, it is useful in sharing ideas
among developers from various domains.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 2 Prepared By Asst.Prof.Bini Charles, TIST


5. Easy translation to a program: Using programming constructs makes mapping the pseudocode
to a program straightforward.
6. Identification of flaws: A pseudocode helps identify flaws in the solution logic before
implementation.

Sequence Algorithm

This is the most elementary construct where the instructions of the algorithm are executed in the order
listed. It is the logical equivalent of a straight line. Consider the code below.
S1
S2
S3
.
.
Sn

The statement S1 is executed first, which is then followed by statement S2, so on and so forth, Sn until
all the instructions are executed. No instruction is skipped and every instruction is executed only once.

Decision or Selection

A selection structure consists of a test condition together with one or more blocks of statements. The
result of the test determines which of these blocks is executed. There are mainly two types of selection
structures, as discussed below:

if structure

Syntax:

if (condition) :
true_instructions
endif

If the test condition is evaluated to True, the statements denoted by true_instructions are executed.
Otherwise, those statements are skipped.

CheckPositive(x)

1 if(x>0):

2 Print(x,“ is positive”)

3 endif

if else structure

if (condition) :
true_instructions
else:
false_instructions
endif

UCEST105- AlGORITHMIC THINKING WITH PYTHON 3 Prepared By Asst.Prof.Bini Charles, TIST


Write an algorithm and pseudocode to determine whether a person is eligible to vote based on their
age.

Algorithm Pseudocode
1. Start START
2. Read the value of age READ(age)
3. If age is greater than or equal to 18 IF age >= 18 THEN
4. Print "You are a major"
5. Else PRINT("You are a major")
6. Print "You are a minor" ELSE
7. End PRINT("You are a minor")
ENDIF
STOP
Program:
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

Write an algorithm and pseudocode to determine whether a number is odd or even.

Algorithm Pseudocode
START
1. Start
READ(number)
2. Read the number
3. If the number is divisible by 2 (i.e., IF number % 2 == 0 THEN
number % 2 == 0) PRINT("The number is even.")
o Print "The number is even." ELSE
4. Else PRINT("The number is odd.")
o Print "The number is odd." ENDIF
5. End STOP
Program:
number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number is even.")
else:
print("The number is odd.")

UCEST105- AlGORITHMIC THINKING WITH PYTHON 4 Prepared By Asst.Prof.Bini Charles, TIST


if else if else structure

When a selection is to be made out of a set of more than two possibilities, you need to use the if else
if else structure, whose general form is given below:

if (condition 1) :
True_instructions 1
else if (condition 2):
True_instructions 2
else:
False_instruction
endif

Here, if condition1 is met, True_instructions1 will be executed. Else condition2 is checked. If it


evaluates to True, true_instructions2 will be selected. Otherwise false_instructions will be executed.

Algorithm Pseudocode

1. Start START
2. Read the values of x and y READ(x, y)
3. If x is greater than y IF x > y THEN
o Print "x is greater than y" PRINT(x + " is greater than " + y)
4. Else if x is less than y ELSE IF x < y THEN
o Print "x is less than y" PRINT(x + " is less than " + y)
5. Else ELSE
o Print "x is equal to y" PRINT(x + " is equal to " + y)
6. End ENDIF
STOP

Program
x = int(input("Enter the value of x: "))
y = int(input("Enter the value of y: "))
if x > y:
print(x, "is greater than", y)
elif x < y:
print(x, "is less than", y)
else:

print(x, "is equal to", y)

UCEST105- AlGORITHMIC THINKING WITH PYTHON 5 Prepared By Asst.Prof.Bini Charles, TIST


Write a program that takes a score as input and prints the corresponding grade using the
following criteria:
Score >= 90: Grade A
Score >= 80: Grade B
Score >= 70: Grade C
Score >= 60: Grade D
Score < 60: Grade F

Algorithm Pseudocode
1. Start
2. Read the value of score START
3. If score is greater than or equal to 90
READ(score)
Print "Grade: A"
IF score >= 90 THEN
4. Else if score is greater than or equal to 80
PRINT("Grade: A")
Print "Grade: B"
ELSE IF score >= 80 THEN
5. Else if score is greater than or equal to 70
PRINT("Grade: B")
Print "Grade: C"
ELSE IF score >= 70 THEN
6. Else if score is greater than or equal to 60
PRINT("Grade: C")
Print "Grade: D"
ELSE IF score >= 60 THEN
7. Else
PRINT("Grade: D")
Print "Grade: F"
ELSE
8. End
PRINT("Grade: F")
ENDIF
STOP

score = float(input("Enter your score: "))


if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
elif score >= 60:
print("Grade: D")
else:
print("Grade: F")

UCEST105- AlGORITHMIC THINKING WITH PYTHON 6 Prepared By Asst.Prof.Bini Charles, TIST


Case Structure

The case structure is a refined alternative to if else if else structure. The pseudocode representation of the case
structure is given below.

The general form of this structure is:

caseof (expression)
case 1 value1:
block1
case 2 value2:
block2
default:
default_block
endcase

Python program, algorithm and pseudocode that prompts the user to enter a number between 1
and 7 and prints the corresponding day of the week.
Algorithm Pseudocode
1. Start.
START
2. Display: "Enter a number (1-7) for
the day of the week:" DISPLAY "Enter a number (1-7) for the day of the week:"
3. Input: Read day_number from user
INPUT day_number
input.
4. Begin caseof structure
on day_number: caseof (day_number)
o Case 1:
§ Print "Monday". case 1:
o Case 2:
PRINT "Monday"
§ Print "Tuesday".
o Case 3: case 2:
§ Print "Wednesday".
PRINT "Tuesday"
o Case 4:
§ Print "Thursday". case 3:
o Case 5:
PRINT "Wednesday"
§ Print "Friday".
o Case 6: case 4:
§ Print "Saturday".
PRINT "Thursday"
o Case 7:
§ Print "Sunday". case 5:
o Default case:
PRINT "Friday"
§ Print "Invalid input!
Please enter a case 6:
number between 1 PRINT "Saturday"
and 7."
5. End caseof structure. case 7:
6. End. PRINT "Sunday"

UCEST105- AlGORITHMIC THINKING WITH PYTHON 7 Prepared By Asst.Prof.Bini Charles, TIST


default:
PRINT "Invalid input! Please enter a number between 1
and 7."
endcase
END
Program
# Start of program
print("Enter a number (1-7) for the day of the week:")
day_number = input()
match(day_number)
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case 4:
print("Thursday")
case 5:
print("Friday")
case 6:
print("Saturday")
case 7:
print("Sunday")
default:
print("Invalid input! Please enter a number between 1 and 7.")
cas

Repetition or loop

When a certain block of instructions is to be repeatedly executed, we use the repetition or loop construct.
Each execution of the block is called an iteration or a pass. If the number of iterations (how many times
the block is to be executed) is known in advance, it is called definite iteration. Otherwise, it is called
indefinite or conditional iteration. The block that is repeatedly executed is called the loop body. There
are three types of loop constructs as they are,

1) while loop
2) repeat-until loop
3) for loop

UCEST105- AlGORITHMIC THINKING WITH PYTHON 8 Prepared By Asst.Prof.Bini Charles, TIST


1) while loop

A while loop is generally used to implement indefinite iteration. The general form of the while loop is as follows:

while (condition) :

(True_instructions)

endwhile

Here, the loop body (true_instructions) is executed repeatedly as long as condition evaluates to True. When the
condition is evaluated as False, the loop body is bypassed.

Write a program that prompts the user to enter a positive integer nn and then calculates and displays the
sum of the first n natural numbers using a while loop.

Algorithm (ALgorithm) BEGIN


1. Start PROMPT user for a positive integer n
2. Input: Prompt the user to enter a positive SET total_sum to 0
integer nn. SET counter to 1
3. Initialize:
o Set total_sum to 0. WHILE counter <= n DO
o Set counter to 1. total_sum = total_sum + counter
4. Loop: counter = counter + 1
o While counter is less than or END WHILE
equal to nn:
§ Add counter to total_sum. PRINT "The sum of the first", n, "natural numbers is:",
§ Increment counter by 1. total_sum
5. Output: Print "The sum of the first", nn, END
"natural numbers is:", total_sum.
6. End

# Prompt the user for a positive integer n


n = int(input("Enter a positive integer: "))
# Initialize total sum and counter
total_sum = 0
counter = 1
# Loop from 1 to n
while counter <= n:
total_sum += counter # Add the counter to total_sum
counter += 1 # Increment the counter
# Print the total sum
print("The sum of the first", n, "natural numbers is:", total_sum)

UCEST105- AlGORITHMIC THINKING WITH PYTHON 9 Prepared By Asst.Prof.Bini Charles, TIST


Write a program that prompts the user to create a password and then asks them to re-enter the
password for confirmation. Use a while loop to continue asking for the confirmation password until
it matches the original password. Once confirmed, display a message indicating that the password
has been successfully set.
Algorithm Pseudocode
1. Start BEGIN
2. Input: Prompt the user to enter a password.
3. Initialize: Set confirm_password to an empty PROMPT user to enter a password
string. SET confirm_password to " "
4. Loop:
WHILE confirm_password does not match
• While confirm_password does not match the password DO
original password:
o Prompt the user to re-enter the PROMPT user to re-enter the password
password. IF confirm_password equals password
o If the re-entered password matches the
original: THEN
§ Print "Password confirmed!" PRINT "Password confirmed!"
§ Exit the loop.
o Else: ELSE
§ Print "Passwords do not match. Please try PRINT "Passwords do not match.
again."
Please try again."
5 End END IF
END WHILE
END
password = input("Enter a password: ")
while True:
confirm_password = input("Re-enter your password to confirm: ")
if confirm_password == password:
print("Password confirmed!")
break
# Exit the loop if the passwords match
else:
print(“Passwords do not match. Please try again.”)

2) repeat-until loop

The second type of loop structure is the repeat-until structure. This type of loop is also used for
indefinite iteration. Here the set of instructions constituting the loop body is repeated as long as
condition evaluates to False. When the condition evaluates to True, the loop is exited. The
pseudocode form of repeat-until loop is shown below.

repeat

False_instructions

until (condition)

UCEST105- AlGORITHMIC THINKING WITH PYTHON 10 Prepared By Asst.Prof.Bini Charles, TIST


Write a program that uses a repeat-until loop to prompt the user to enter a number. The program should
continue asking for a number until the user enters a positive integer (greater than zero). Once a valid
number is entered, the program should display the square of that number

Algorithm (Algorithm) Pseudocode


1. Start
2. Initialize: Set number to -1 (or any
negative value). BEGIN
3. Repeat: SET number to -1
o Prompt the user to enter a REPEAT
positive integer. PROMPT user to enter a positive integer
o Read the input and store it READ number
in number.
UNTIL number > 0 // Loop until a valid input is received
4. Until: Check if number is greater than
0. // Calculate the square of the valid number
5. Calculate: Compute the square SET square to number * number
of number. // Output the result
6. Output: Print the square of the number. PRINT "The square of", number, "is:", square
7. End END

Difference Between While Loop and Repeat- Until Loop

Feature While Loop Repeat-Until Loop

Condition is tested at the


Condition Evaluation Condition is tested at the end
beginning

Continues as long as condition


Loop Control Stops when condition becomes True
is True

May not execute if the condition is Executes at least once regardless of the
Execution Guarantee
initially False condition

Type of Control Entry controlled loop Exit controlled loop

3) for loop
The for loop implements definite iteration. There are three variants of the for loop. All three for loop
constructs use a variable (call it the loop variable) as a counter that starts counting from a specific value
called begin and updates the loop variable after each iteration. The loop body repeats execution until the
loop variable value reaches end.
Iterating Over a Sequence

for variable in sequence:


# Code to execute for each item in the sequence

UCEST105- AlGORITHMIC THINKING WITH PYTHON 11 Prepared By Asst.Prof.Bini Charles, TIST


Ex: fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output
apple
banana
cherry
Using Range
for i in range(start, stop, step):
# Code to execute for each value of i
Ex:
for i in range(1, 6): # This will iterate from 1 to 5
print(i) # Output: 1, 2, 3, 4, 5
range()
The range() function in Python is used to generate a sequence of numbers. It is commonly used
in for loops to iterate a specific number of times or to create a sequence of numbers.
range(start, stop, step)

• start: (optional) The starting value of the sequence (inclusive). Defaults to 0.


• stop: The end value of the sequence (exclusive).
• step: (optional) The increment between each number in the sequence. Defaults to 1.

Example Output

range(5) 0, 1, 2, 3, 4

range(2, 8) 2, 3, 4, 5, 6, 7

range(0, 10, 2) 0, 2, 4, 6, 8

range(5, 0, -1) 5, 4, 3, 2, 1

range(1, 20, 3) 1, 4, 7, 10, 13, 16, 19

list(range(1, 6)) [1, 2, 3, 4, 5]

list(range(2, 21, 2)) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

UCEST105- AlGORITHMIC THINKING WITH PYTHON 12 Prepared By Asst.Prof.Bini Charles, TIST


Write a program that prompts the user to enter a positive integer n and then calculates and prints
the sum of the first n natural numbers.
Algorithm Pseudocode
BEGIN
1. Start
2. Input: Prompt the user to enter a positive integer n. PROMPT user to enter a positive integer n
3. Initialize: Set total_sum to 0. READ n
4. For Loop: Iterate from 1 to n:
o Add the current number to total_sum. SET total_sum to 0
5. Output: Print total_sum. FOR i FROM 1 TO n DO
6. End
total_sum = total_sum + i
PRINT total_sum
END
END
CODE
n = int(input("Enter a positive integer: "))
total_sum = 0
for i in range(1, n + 1):
total_sum += i
print("The sum of the first", n, "natural numbers is:", total_sum)

UCEST105- AlGORITHMIC THINKING WITH PYTHON 13 Prepared By Asst.Prof.Bini Charles, TIST


Flowcharts
A flowchart is a diagrammatic representation of an algorithm that depicts how control flows in it.
Flowcharts are composed of various blocks interconnected by flow-lines. Each block in a flowchart
represents some stage of processing in the algorithm. Different types of blocks
are defined to represent the various programming constructs of the algorithm.

► Terminator : A terminator symbol is used to represent the beginning and


end of an algorithm

►Connector Lines: Connector lines are used to connect symbols in the


flowchart.
► The direction of the arrow indicates the next step.

► Process: A process symbol : represents an activity. It represents a particular


step of an algorithm.
► The symbol contains text which describes the step.

► Decision: A symbol used to branch into different steps based on condition


► Based on whether the condition succeeds or fails, connector lines connect to
different points in the flowchart.

►On page and Off Page References: Symbols used when the entire
flowchart cannot fit on the same page fully.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 14 Prepared By Asst.Prof.Bini Charles, TIST


Rectangle with vertical side-lines denotes a module. A module is a
collection of statements written to achieve a task. It is known by
the name function in the programming domain.

Hexagon denotes a for loop. The symbol shown here is the


representation of the loop: for count = A to B by S.

To find simple interest.

To determine the larger of two numbers.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 15 Prepared By Asst.Prof.Bini Charles, TIST


To determine the smallest of three numbers.

To determine the entry-ticket fare in a zoo based on age as follows:

UCEST105- AlGORITHMIC THINKING WITH PYTHON 16 Prepared By Asst.Prof.Bini Charles, TIST


To print the colour based on a code value as follows:

To find the factorial of a number


Solution: The factorial of a number n is defined as n! = n×n−1×· · · · · ·×2×1.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 17 Prepared By Asst.Prof.Bini Charles, TIST


To find the factorial of a number
Solution: The factorial of a number n is defined as n! = n×n−1×· · · · · ·×2×1.

To find the average height of boys and average height of girls in a class of n students.

UCEST105- AlGORITHMIC THINKING WITH PYTHON 18 Prepared By Asst.Prof.Bini Charles, TIST


UCEST105- AlGORITHMIC THINKING WITH PYTHON 19 Prepared By Asst.Prof.Bini Charles, TIST
Exercises

UCEST105- AlGORITHMIC THINKING WITH PYTHON 20 Prepared By Asst.Prof.Bini Charles, TIST

You might also like