0% found this document useful (0 votes)
244 views21 pages

Chapter 2

Uploaded by

sabahamza97
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)
244 views21 pages

Chapter 2

Uploaded by

sabahamza97
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/ 21

Prof.

Muhammad Zubair Zaib

Chapter:2 Computational Thinking & Algorithm

Q: What is Computational Thinking & Algorithms? Discuss Different Properties of


Computational Thinking:

Computational thinking is a thought process that helps us to understand the problem and solve it as a
computer can do. A computer works on the input-process-output model.

Computational thinking consists of the following properties:

a) Decomposition
b) Pattern Recognition
c) Abstraction
d) Algorithm
a) Decomposition:
The process of breaking down a complex problem into smaller and more manageable tasks/sub problems is
called decomposition. Decomposition makes easier to understand and solve each part of the problem
individually.

Example:

Developing Mobile App

• Designing User interface

• Coding of Specific features (Login, navigation)

• Handling data storage

b) Pattern Recognition:

The Process of identifying patterns, and trends within data or problems. Recognizing these patterns helps in
predicting outcomes and making informed decisions.

Example:

Meteorologists analyze weather patterns to predict future weather conditions.

Recognizing patterns of historical Weather data includes:

• Temperature

• Humidity

• atmospheric pressure

By using the above data Meteorologists can forecast events like storms, heatwaves, and rainfall.
Prof. Muhammad Zubair Zaib

c) Abstraction:

The process of ignoring unnecessary details and focusing on the most relevant aspects of the problem is
called abstraction. This helps in managing complexity and making easir to solve the problem.

Example:

Creating a website

Focusing on main design and functionality without getting into code details. Thinking about:

• Layout of website

• Colour Scheme of website

• User interface etc.

d) Algorithm:

Developing a step-by-step solution to solve a problem

Q: What Computational Artifacts? How Computational Artifacts Used in Software


Development:

• It is a creative development process that refers to the creation of digital objects and systems by using
different computational techniques and tools.
• Computational artifacts could be programs, websites, videos, simulations, databases, digital animation,
e-commerce platforms, and mobile apps etc.

Computational Artifacts in Software Development:

• In software development, computational artifacts are the various digital products that are created
during the process of designing, coding, testing, and maintaining of software.
• These artifacts can be code, documents, diagrams, images, prototype and meeting notes etc.
Prof. Muhammad Zubair Zaib

Q: How do we design a computation solution?

Computational solution design is the process of creating and planning strategies and methodologies to solve
computational problems.

The following are the commonly used computational solution desing:

a) Design Methods.
b) Algorithm Design

a. Design Methods

Design Methods consist of the following parts:

• Algorithms
• Flowcharts
• Pseudocode

Algorithms:
An algorithm is a step-by-step procedure to find the solution to a problem.
Example:
Find the student’s result
1. Start
2. input marks
3. If marks are greater than 40 display pass else display fail
4. End

Flow Chart:
The diagrammatic/graphical representation of the algorithm is called a flow chart.

Example:
Prof. Muhammad Zubair Zaib

Pseudocode:
• Pseudocode is a high-level, informal way of describing the steps of an algorithm or program.
• It uses a simplified, human-readable syntax that is not linked to any specific programming language.
• It focuses on the logic and flow of the algorithm.

Example:

// Read the first number from the user

Print "enter the first number: "

Set number 1 to input()

// read the second number from the user

Print "enter the second number: "

Set number2 to input()

// calculate the sum of the two numbers

Set sum to number1 + number2

// display the result

Print "the sum of", number1, "and", number2, "is", sum

b. Algorithm Design

• The primary goal of pseudocode is to understand the logic of an algorithm in clear and specific
programming language conventions.

• Pseudocode writing is not a standardized set of rules; however, some sets of guidelines are often
followed:

i) Font, Size, Style:

Font: plain, easy to read

Size: 10-12 points

Style: Italic and bold keywords → (not a strict rule)

ii) Indentation:

2-4 spaces or a tab character is used for each level of indentation.


Prof. Muhammad Zubair Zaib

iii) Case:

Pseudocode is not case-sensitive, Upper-case letters and lower-case letters can be used. Mostly Keywords
in Uppercase letters and variables in lowercase letters.

iv) Line Numbers:

It is optional and mostly depends on personal preference or requirement. Line numbers can assist the reader
in understanding the logic of the algorithm.

v) Comments:

Comments are essential for explaining the logic of the algorithm. They are often denoted by symbols like
// for single-line comments and /* */ for multiline comments.

vi) Datatype of Keywords:

Some pseudocode styles use datatypes for different types of data such as INTEGER, STRING, FLOAT
etc. but it is optional.

vii) Variable Assignments and Declarations:

The variable can be declared by using the DECLARE keyword and the assignment is denoted by = sign

viii) Common Operators:

+, -, *, / ,=, <, >, <=, >=, != represent common operations.

ix) Key Commands:

Key commands like INPUT, OUTPUT, IF, WHILE, FOR can be used to represent any action

Q: Planning and Developing a Computational Artifact:

The following steps are used to develop a computational artefact.

a. Define the problem:


Address the problem clearly and concisely.

b. List of Inputs:

Information (Input) needed to solve the problem and expected output (Algorithm used to

produce output)

c. Plan:

i) Outline the Logic: Break the problem into smaller parts and make a plan for how to solve these
problems
Prof. Muhammad Zubair Zaib

ii) Choose Data Structures: A data structure is a storage mechanism that is used to store and organize
data. We can choose different data structures such as arrays, stacks, queues, etc.

iii) Choose Control Structures: to control the execution of the program, the following control structure
can be used:

• Conditional Structure: used when some statements are selected and some are skipped.
• Loops/Iterations: used when one or more statements are repeated
d. Development:

• Describe the steps needed to convert the inputs and produce the output after the processing.

• Start at a high level first and keep refining the steps until they reach the computable operations.

• Keep the process simplified and the number of steps should be finite.

e. Test the Algorithm:

Choose the data set and verify whether your algorithm is working properly or not
Prof. Muhammad Zubair Zaib

Example:
Jeroo is a kangaroo-like animal. A Jeroo can pick flowers from one location and plant them to
others. The Jeroo moves by hopping in four directions e.g. forward, backward, right and left. As
the Jeroo hops; it must avoid water, net, and other hurdles.

Problem Definition:
Consider the given diagram, where the field is divided into a 5x5 matrix and a Jeroo is available at
the position (0,0) facing East. The flower is located at (3,0). Write an algorithm where the Jeroo
picks the flower and plant to another location(3,2). After its plantation, the Jeroo should move one
hop East and stop there. Assume no other Jeroo, flowers or nets are available in the field.
The top left corner of the matrix is the (0,0) value of x increases horizontally and y
downwards.
Prof. Muhammad Zubair Zaib

Testing Computational Artifacts:


• Testing Computational Artifacts means the evaluation of a digital product or system whether a system
has some logical error or not.
• E.g. we should consider what happens if a user enters invalid or out-of-range output.
• Testing is an iterative process which helps in the refinement of the solution of a computational artifact.

a) Tracing an Algorithm:
• Tracing of an Algorithm is also known as a “Desk check or Dry run”.
• The programmer converts the algorithm into code and writes it on a compiler for execution.
• Before converting and writing a program on the compiler user manually verifies the working of an
algorithm.
• In tracing we simulate the execution of the algorithm and keep track of all the variables values and
flow logic control.
• The following steps are involved in the Tracing of an algorithm.
a. Understand the Algorithm
b. Choose Test input
c. Initialization
d. Trace Each Step:
e. Repeat until Completion:
f. Verify output

Trace Table:
The dry run of an algorithm can be done with a technique known as a “Trace Table”.
• In this technique, the change in variable values is listed in the table.
• The trace table generates the output on the base of the given input data set.
• It also helps to check that our logic is correct or not, and find logical errors, if any.
Prof. Muhammad Zubair Zaib

Example:
Pseudocode:

1. INPUT Number=3

2. PRINT Number

3. FOR i from 1 to 3

4. Number=Number+5

5. PRINT Number

6. PRINT “END”

b) Algorithm Evaluation Parameters:


• Algorithms are evaluated by using different criteria and methods to assess their performance,
efficiency and correctness for specific tasks.
• The evaluation process determines whether the algorithm meets its objectives or not.
The following are some common ways to evaluate algorithms:

1. Correctness:
Correctness means the algorithm must produce the desired output for all possible valid inputs.
Therefore, various inputs are used during the evaluation of an algorithm.

2. Efficiency:
Efficiency deals with the time and space (amount of memory) complexity of an algorithm.
Time Complexity: The amount of time taken by an algorithm to run
Space Complexity: The amount of memory required by the algorithm to run.

3. Clarity:
Clarity means how easily the steps and logic of an algorithm is understood by a human.

4. Reliability:
Reliability refers to the ability of an algorithm to produce correct and accurate results each time we
execute it. A reliable algorithm should be accurate and consistent in terms of performing tasks.
Prof. Muhammad Zubair Zaib

Common Computing Algorithm:


• Different problems require different types of algorithms to solve the problem.
• Many pre-developed algorithms are used because they solve daily life problems. A few of them are
discussed below:

1. Sorting Algorithm:
• Sorting is a process of arranging the values in a specific sequence/Order.
• There are two types of sorting used ascending order sorting and Descending order sorting.

There are two types of sorting algorithms are used

• Insertion Sort
• Bubble Sort

1.1 Insertion Sort Algorithm:


• Insertion sort is a technique in which we compare two adjacent elements and sort them if they are not
in the correct order.
• In comparison, the smallest element is selected and swapped with the element placed at the first
location.
• This is the first iteration, and we will continue until all elements are sorted.
• At the end we have an array of sorted elements.

Working:
• Suppose we have an unsorted Array
Prof. Muhammad Zubair Zaib

Step-1:
Select the 1st element and compare it with the next adjacent element.

Now compare 33 with 77, as 33 < 77 now shift/swap 33 in place of 77

Step-2 :

Now compare 44 With 77, as 44 < 77 now shift/swap 44 in place of 77

Step-3:

Now compare 11 With 77, 11< 77, 11<44, and 11< 33 now shift/swap 11 in place of 33
Prof. Muhammad Zubair Zaib

Step-4:

Now compare 88 77 , as 88> 77, 88>44, 88>33 and 88>11, there is no need to shift/swap any element. An
array is already sorted

Insertion Sort in Context of Computational Thinking:


1. Abstraction:
Organize a collection of items by repeatedly picking up each item and inserting into it its correct
position.
2. Decomposition:
Sub-Processes:
Pick and Insert: For each item, pick it up and insert it into the sorted collection.
Correct Position Logic: Determine the correct position for each item in the sorted collection.
3. Pattern Recognition:
Repetition: The process involves repeating the steps for each item.
Building Order: The algorithm focuses on building a sorted collection incrementally.
Ordered Comparison: It employs comparisons to determine the correct position.
4. Algorithm Design:
1. Start with 2nd element of the array.
2. compare 2nd element with the 1st element.
3. check it the 2nd element is smaller than 1st element then swaps them.
4. Move to the next element and compare it with sorted part.
5. Swap as necessary to put it in the correct position among the sorted part.
6. Repeat these steps for each element in the array, until the array is in sorted order.
Prof. Muhammad Zubair Zaib

1.2 Bubble Sort Algorithm:


• Bubble sort is also known as “Exchange Sort”.
• It repeatedly visits the array and compares two items at a time.
• It swaps these two items if they are wrong in order.
• It continues to visit the array until no swaps are needed which means the array is sorted.

Working:
Suppose we have an unsorted Array

Pass-1
Step-1:
Select the 1st two elements from the array and compare them

As 33<77 So swap these two values

Step-2:

Compare the next two adjacent elements

As 44<77 So swap these two values


Prof. Muhammad Zubair Zaib

Step-3:

Compare the next two adjacent elements

As 11<77 So swap these two values

Step-4:
Compare the next two adjacent elements

As 88>77 So we will not swap these two values the values remain on their current locations

Now again moves to the 1st location(index) of an array and repeat the process againPass-3
Step-1:
Select the 1st two elements from the array and compare them
Prof. Muhammad Zubair Zaib

As 11<33, we will swap these two values.

As the array is sorted, there is no need to perform step 4 or proceed to the next Pass.

Bubble Sort in Context of Computational Thinking:


1. Abstraction:
Organise a collection of items by repeatedly comparing and swapping adjacent elements until the
whole group is sorted.
2. Decomposition:
Sub-Processes:
Adjacent Comparison: compare each pair of neighboring items
Swap logic: if pairs are in the wrong order swap them.
Iteration: repeat these steps until the entire group is sorted.
3. Pattern Recognition:
Pairwise Comparison: The algorithm focuses on comparing the adjacent pair of elements
Iterative process: The sorting process is achieved through multiple iterations
Repeating Patterns: The comparison and swapping is repeated until all the items are sorted in order.
4. Algorithm Design:
1. Start with the 1st element in the array.
2. make a pair of 1st element with 2nd (next) element. Now compare these adjacent elements.
• If the first element is greater than the next one, swap them.
• If not, move on to the next pair
3. Repeat the comparing and swapping process for each pair of the elements in the array
4. each pass ensure that largest unsorted item moves to its correct position at the end of list
5. Continue these steps, excluding already sorted elements, until the entire array is sorted.
Prof. Muhammad Zubair Zaib

6. the number of passes needed is one less than total number of items in the list.

When to use which Algorithm:

2. Searching Algorithm:
• The process of finding desired elements from a group of elements is called searching.
• The following searching algorithms are used:
❖ Sequential Search
❖ Binary Search
Example:
Search 3 from Array

Sorted Output

Item 3 is found at index 2

2.1 Sequential Search Algorithm:


• Sequential Search is also called “Linear Search” or “Serial Search”.
• It is a simple way to search an array for the desired value.
• The following steps are used to search for a value in an array.
Prof. Muhammad Zubair Zaib

1. Visit the first element of the array and compare its value with the required value.
2. If the value of the array matches the desired value, the searching is complete.
3. If the value does not match, move to the next element and repeat the same process.
Working:
Consider the given unsorted array and we need to find the location of item 44.

Step-1:
Select the 1st element of an array and compare it with desired value that we want to search. If the values
match the searching will be completed.

32 is not equal to 44 so we will move to the next element.


Step-2:
Now select the 2nd element of an array and compare it with the desired value that we want to search. If the
values match the searching will be completed.

10 is not equal to 44 so we will move to the next element.


Step-3:
Now select the 3rd element of an array and compare it with the desired value that we want to search. If the
values match the searching will be completed.

44 is equal to 44 the value found at index 2.


Now the searching process is completed no need to move to the next element.
Prof. Muhammad Zubair Zaib

Linear Search Algorithm in Context of Computational Thinking:


1. Abstraction:
Search a specific item in a sequence by checking each item in the array until the target item is found.
2. Decomposition:
Sub-Processes:
i. Starting Point: Begin searching from 1st Item.
ii. Item Checking: inspect or check each item to see if it matches or not.
iii. Stopping Condition: Stop when the target is found or the end of the array is reached
3. Pattern Recognition:
i. Sequential Nature: The process starts sequentially and checks each item at a time.
ii. Linear Progression: The search progresses linearly through each item of an array
iii. Terminated condition checked: The Search stops when the target is found or the end of an array is
reached.
4. Algorithm Design:
1. Start from the beginning of the array.
2. Check if the current element is equal to the target value
• if it is, the target is found
• if it is not moved to the next element in a sequence
3. Repeat step 2 until the target value is found or reached at the end of the array.
4. If you reach the end without finding the targeted value, the targeted value does not exist in an array.

2.2 Binary Search Algorithm:


• Binary Search method works on a sorted array.
• It works on the divide and conquer rule in which a sorted list is divided into two parts.
• Binary search is a quicker method of searching a value from the array.
• It takes less time than a sequential search.
It follows the following steps:
▫ It locates the middle element of an array and compares it with the search number.
▫ If they are equal, the search is successful and the index of the middle element is returned.
▫ If they are not equal, reduce the search to half of the array.
▫ If the search number is less than the middle element, the first half of the array is searched
otherwise the 2nd half of the array is searched.
▫ The process continues until the number is found.
Prof. Muhammad Zubair Zaib

Working:
Consider the given sorted array and we need to find the location of item 69.

Step-1:

First of all find the middle element of an array.


mid= (start + end)/2 → 2
So the middle element is 2

Step-: 2
Now check whether the value of the middle element is equal to the desired value or not.

As 29 is not equal to 69 and the search is unsuccessful now the array is reduced into two half

Step-: 3
Prof. Muhammad Zubair Zaib

As we see that the search number 69 is greater than the value of the middle element 29 the searching
process will be performed on 2nd half of the array.

Step-4:

Now again find the middle element of 2nd half of array


mid= (start + end)/2 → (3+4)/2 ➔ = 3

Step-5:

Now check whether the value of the middle element is equal to the desired value or not

As 35 is not equal to 69 and the search is unsuccessful now the array is reduced into two halves.

Step-: 6
As we see that the search number 69 is greater than the value of the middle element 35 the searching
process will be performed on 2nd half of the array.

Only one element remains in an array so it value matches with the desired value so there is no need to
perform further steps. The desired value 69 is found at index 4.
Prof. Muhammad Zubair Zaib

Binary Search Algorithm in Context of Computational Thinking:


1. Abstraction:
Finding a specific item in a sorted array by splitting the search area in half until the item is found or there
is no more space to search.
2. Decomposition:
Sub-Processes:
i. Middle item check: Find the middle item by using a formula, mid= (start + end)/2 and match
the middle element value with the target
ii. Searching Space division: Divide the search area based on a comparison result
iii. Recursive Process: Repeat the process and narrow down the search space.
3. Pattern Recognition:
Having a search space: the main idea is to reducing the search space by half
4. Algorithm Design:
1. Start with the entire sorted array.
2. Check the middle element of the array:
• if it is equal to the target value, you are done.
• If it is greater than the targeted value, ignore the right half of the array.
• If it is less than the targeted value, ignore the left half of the array.
3. Repeat the process on the remaining half.
4. Continue until the target is found, or the array becomes empty.

When to use which Algorithm:

You might also like