0% found this document useful (0 votes)
32 views12 pages

Unit 2 Complete Notes

Uploaded by

madeehamansoor66
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)
32 views12 pages

Unit 2 Complete Notes

Uploaded by

madeehamansoor66
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

Chapter 2

Computational thinking and algorithms


Q: What is a computer problem and problem solving?
A problem is a challenge or situation for which a solution is required. The process of analyzing that situation
and accordingly handling it is referred as problem solving.
Q: What is computational thinking?
Computational thinking is a thought process that helps us to understand the problem and solve it in a way that
computers do.
Q: What are the properties of computational thinking?
The solution of a problem where computational thinking is applied uses the following properties:
Abstraction: Simplifying a problem or system by focusing on the most relevant aspects while ignoring
unnecessary details. Consider the task of Creating a website Abstraction is to focus on the main design and
functionality without getting into the coding details
Decomposition: Breaking down a complex problem into smaller, more manageable sub-problems or tasks.
Consider the task of Developing a mobile app Decomposition is to break the task into smaller parts like
designing the user interface, coding specific features.
Pattern Recognition: Identifying patterns or trends within data, problems, or solutions. Pattern Recognition is
to identify trends, such as which pages users visit the most or common paths they take. This helps in making
improvements based on observed patterns.
Algorithmic Design: Developing a step-by-step solution to solve a problem.
Q: What are computational artifacts?
Computational artifacts refer to human made objects and systems using computational thinking. An artifact is
a byproduct of software. Particularly in computer science, the computational artifacts could include programs,
websites, videos, simulations, databases, digital animations, software systems, e-commerce platforms, and
mobile applications.
Q: What are algorithms, flow charts, pseudocode
Algorithms: An algorithm is a step-by-step set of instructions that defines how a specific problem should be
solved. It is a high-level description of the solution without worrying about the implementation details such as
specific programming language. Algorithms are normally written in natural language.
Flow Chart: This provides a visual representation of flow and logic using defined symbols. Flowcharts are
mostly helpful in explaining complex loops and decision- making processes.
Pseudocode: Pseudocode is an intermediate step between the algorithm and actual programming code. It's a
more structured and semi-formal way of representing the algorithm using a combination of natural language
and simplified programming constructs. Pseudocode helps in explaining the logic and structure of the
algorithm before starting programming.
Q: What are the steps in Planning and Developing a Computational Artifact?
The following steps are used for planning and development of an artifact.
a. Define the problem: State the problem you are trying to solve in clear and concise terms.
b. List the inputs (information needed to solve the problem) and the expected outputs (what the algorithm
will produce as a result)

Class: XI Page 1 of 12 Computer Science (Chapter#2)


c. Plan:
i) Outline the logic: For this purpose, breakdown the problem into smaller problems and consider how to
solve each one.
ii) Choose Data Structures: A data structure is a storage to save and organize the data. We have different
types of data structures such as array, stack, queue, etc.
iii) Choose Control Structures: enables to determine the order of program execution. The sequential order of
execution is disturbed in two aspects: skip some program statements. This is usually done with the help of
conditional statements. Repeat one or more program statements. This is done by using loops.
d. Development: Describe the steps needed to convert or manipulate the inputs to produce the outputs. Start
at a high level first and keep refining the steps until they are effectively computable operations. Keep the
process simplified and remember that the number of steps should be finite.
e. Test the algorithm: choose data sets and verify that your algorithm.

Q: What is meant by tracing of algorithm?


Tracing of algorithm is also known as a "desk check or dry-run". Before going to write code for an algorithm,
manually verify that the algorithm works correctly. For this purpose, trace method is used that hand simulate
the execution of your algorithm, keep change track of variable values and flow of logic control. Tracing of
Algorithm involves the following:
a. Understand the Algorithm: Before tracing is started, thoroughly understand the algorithm's logic flow.
b. Choose Test Input: To trace the algorithm it requires input; a complete set of input is there- fore chosen at
this point.
c. Initialization: Initialize the variables and data structures.
d. Trace Each Step: hand execute the algorithm step-by-step, tracking the flow of control.
For each step of algorithm, do the following:
 Track record Inputs:
 Perform processing:
 Update Variables:
 Go by Control Flow:
e. Repeat Until Completion: Tracing the algorithm continues step by step until we reach the end of algorithm.
f. Verify Output: At the end, evaluate the final output and ensure that it matches our expectations.

Class: XI Page 2 of 12 Computer Science (Chapter#2)


Q: Draw trace table for
the following pseudo
code
Pseudocode

1. Start
2. Set c=1 3
Read n
4. m=n*c
5. print m
6. C=C+1
7. Repeal steps 4 to 6
while (c<=10)
8. End

Pseudocode Example: Sum of first n


natural numbers
START
SET sum = 0
SET i = 1
INPUT n
WHILE i <= n DO
sum = sum + i
i = i + 1
END WHILE
OUTPUT sum
END

Q: What is meant by algorithm evaluation? What are Algorithms Evaluation Parameters


The evaluation process determines whether an algorithm meets its intended objectives.
The following are some common ways to evaluate algorithms, however at advanced level there are many
other ways also.
Correctness: An algorithm must produce the desired output for all possible valid inputs.
Class: XI Page 3 of 12 Computer Science (Chapter#2)
Efficiency: Efficiency of an algorithm deals with time and space (amount of memory) complexity. The time
complexity refers to the amount of time taken by an algorithm to run and space complexity refers to the
amount of memory required to run that algorithm.
Clarity: This refers to how easily the algorithm's logic and steps can be understood by humans
Reliability: Reliability refers to the ability to always produce correct and accurate results when the algorithm is
given a set of inputs.
Q: Discuss following algorithms
Insertion sort

Insertion Sort is a simple, intuitive, and efficient comparison-based sorting algorithm that builds the final
sorted array one element at a time. It is similar to how you might sort playing cards in your hand, starting with
an empty hand and then picking one card at a time and inserting it into its correct position relative to the other
cards you've already sorted.

How Insertion Sort Works:

1. Start with the second element of the array (assuming the first element is already "sorted").
2. Compare the current element with the elements before it (to the left).
3. Shift all elements greater than the current element one position to the right to make space.
4. Insert the current element into its correct position.
5. Repeat this process for all remaining elements until the entire array is sorted.

Example:

Let’s say we want to sort the array: [5, 2, 9, 1, 5, 6].

1. Initial array: [5, 2, 9, 1, 5, 6]


2. Start with the second element 2:
o Compare 2 with 5. Since 2 < 5, shift 5 to the right and place 2 at the first position.
o Array after first iteration: [2, 5, 9, 1, 5, 6]
3. Move to the next element 9:
o Compare 9 with 5. Since 9 > 5, leave it in place.
o Array after second iteration: [2, 5, 9, 1, 5, 6]
4. Move to the next element 1:
o Compare 1 with 9, 5, and 2. Since 1 < all of them, shift them right and insert 1 in the first
position.
o Array after third iteration: [1, 2, 5, 9, 5, 6]
5. Move to the next element 5:
o Compare 5 with 9. Since 5 < 9, shift 9 right and place 5 in its correct position.
o Array after fourth iteration: [1, 2, 5, 5, 9, 6]
6. Move to the next element 6:
o Compare 6 with 9. Since 6 < 9, shift 9 right and place 6 in its correct position.
o Array after fifth iteration: [1, 2, 5, 5, 6, 9]

Final Sorted Array: [1, 2, 5, 5, 6, 9]

Class: XI Page 4 of 12 Computer Science (Chapter#2)


Bubble Sort

Bubble Sort is a simple comparison-based sorting algorithm that repeatedly steps through the list, compares
adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted.

The name "bubble sort" comes from the way larger elements "bubble" to the top of the list, as they are swapped
with smaller elements.

How Bubble Sort Works:

1. Start from the beginning of the list.


2. Compare the first two adjacent elements:
o If the first is greater than the second, swap them.
o If not, move to the next pair.
3. Repeat this process for all pairs in the list.
4. After each pass through the list, the largest unsorted element is placed at the end.
5. Repeat the process for the remaining unsorted elements, reducing the range of comparison by one in
each iteration.
6. The algorithm stops when no more swaps are needed, meaning the list is fully sorted.

Example:

Let’s sort the array: [5, 2, 9, 1, 5, 6].

1. Initial array: [5, 2, 9, 1, 5, 6]


2. First pass:
o Compare 5 and 2. Since 5 > 2, swap them: [2, 5, 9, 1, 5, 6].
o Compare 5 and 9. No swap needed: [2, 5, 9, 1, 5, 6].
o Compare 9 and 1. Swap them: [2, 5, 1, 9, 5, 6].
o Compare 9 and 5. Swap them: [2, 5, 1, 5, 9, 6].
o Compare 9 and 6. Swap them: [2, 5, 1, 5, 6, 9].
o Largest number 9 is now in the correct position.
3. Second pass:
o Compare 2 and 5. No swap needed: [2, 5, 1, 5, 6, 9].
o Compare 5 and 1. Swap them: [2, 1, 5, 5, 6, 9].
o Compare 5 and 5. No swap needed: [2, 1, 5, 5, 6, 9].
o Compare 5 and 6. No swap needed: [2, 1, 5, 5, 6, 9].
4. Third pass:
o Compare 2 and 1. Swap them: [1, 2, 5, 5, 6, 9].
o Compare 2 and 5. No swap needed: [1, 2, 5, 5, 6, 9].
o Compare 5 and 5. No swap needed: [1, 2, 5, 5, 6, 9].

Now the array is fully sorted.


Final Sorted Array: [1, 2, 5, 5, 6, 9]

Q: Discuss when to use bubble and insertion sort.

Class: XI Page 5 of 12 Computer Science (Chapter#2)


Criteria Bubble Sort Insertion Sort
Efficiency on Small More efficient than Bubble Sort for small
Suitable for very small datasets.
Data datasets.
Efficiency on Large Inefficient for large datasets time Inefficient for large datasets, but slightly faster
Data complexity). than Bubble Sort.
Performs poorly even on nearly sorted
Nearly Sorted Data Works very efficiently on nearly sorted data.
data.
Simple but requires a bit more logic than
Simplicity Very simple and easy to implement.
Bubble Sort.
Educational purposes or when Better choice for small or nearly sorted data
Use Case
simplicity is needed. sets.

Summary:

 Use Bubble Sort: For educational purposes or very small datasets where simplicity is a priority.
 Use Insertion Sort: When dealing with small or nearly sorted datasets for better efficiency.

Binary Search

Binary Search is an efficient search algorithm used to find the position of a target element in a sorted array. It
repeatedly divides the search interval in half, eliminating half of the remaining elements with each step.

How Binary Search Works:

1. Initial Setup: The search begins by looking at the middle element of the sorted array.
2. Comparison:
o If the middle element is the target, the search is successful.
o If the target is less than the middle element, the search continues in the left half of the array.
o If the target is greater than the middle element, the search continues in the right half of the array.
3. Repeat: This process is repeated until the target element is found or the sub-array becomes empty.

Example:

Let’s say we want to search for the number 7 in the sorted array [1, 3, 5, 7, 9, 11].

1. Initial array: [1, 3, 5, 7, 9, 11]


o So, we search the right half of the array: [7, 9, 11].
2. Next step:
o array[4] = 9, which is greater than 7.
o So, we search the left half of this subarray: [7].
3. Final step:
o array[3] = 7, which matches the target.
o Target found at index 3.

Linear Search

Linear Search is a simple search algorithm used to find a target element within a list or array. It works by
checking each element in the list one by one until it finds the target or reaches the end of the list.
Class: XI Page 6 of 12 Computer Science (Chapter#2)
How Linear Search Works:

1. Start at the first element of the list.


2. Compare the current element with the target element.
3. If the current element matches the target, the search is successful, and its index is returned.
4. If it doesn't match, move to the next element and repeat the process.
5. Continue until the target is found or the list is fully traversed.

Example:

Let’s say we want to search for the number 7 in the array [1, 3, 5, 7, 9, 11].

1. Initial array: [1, 3, 5, 7, 9, 11]


o Compare 1 with 7. No match.
o Compare 3 with 7. No match.
o Compare 5 with 7. No match.
o Compare 7 with 7. Match found.
2. The target 7 is found at index 3.

Key Characteristics:

 Works on both sorted and unsorted data: Unlike binary search, linear search doesn't require the data
to be sorted.
 Inefficient for large datasets: Since it checks each element individually, linear search becomes
inefficient for large datasets.
 Simple to implement: The algorithm is straightforward and easy to implement.

Exercise
Give Short answers.
Q: 1 Differentiate between

i. Clarity vs. efficiency

In computational thinking, clarity focuses on making an algorithm or solution easy to understand and maintain, while
efficiency emphasizes optimizing the algorithm for speed and resource usage. Sometimes, a clear solution might be less
efficient, and improving efficiency can make the solution harder to understand. The goal is to balance both based on the
problem's needs.

ii. Abstraction vs. pattern recognition


Feature Abstraction Pattern Recognition
Definition Simplifying a complex system by focusing on the essential Identifying similarities, trends,
details and ignoring irrelevant ones. or regularities in data or
processes.
Purpose To reduce complexity and focus on the core idea or To detect recurring patterns or
structure. behaviors in data.
Focus Generalization and simplification of details. Finding relationships and
trends within data.
Use in Problem Helps in creating models or representations by Aids in predicting future
Solving eliminating unnecessary details. behavior or classifying data
based on recurring patterns.
Class: XI Page 7 of 12 Computer Science (Chapter#2)
Example Defining a car as a vehicle with wheels and an engine, Recognizing that temperatures
ignoring color, brand, or other non-essential details. follow a seasonal pattern each
year.
Goal To create a simple representation of a complex system. To find commonalities or
repeated sequences in data.

iii. Pseudocode vs. Flowchart

Feature Pseudocode: Flowchart:


Definition: A high-level description of an algorithm or A diagrammatic representation of an
program using plain, informal language algorithm or process, where different
that resembles programming logic. It symbols are used to represent steps,
focuses on the logic without adhering to decisions, and the flow of control.
any specific programming syntax
Representati Written in plain text, usually in structured A graphical representation using shapes
on: format with indents or bullet points to like ovals, rectangles, diamonds, and
represent the steps. arrows to indicate the flow of the
algorithm.
Ease of Easier for those with a programming Useful for those who prefer graphical
Understandi background explanations of processes.
ng:
Purpose: Helps programmers design an algorithm Helps visualize the flow and structure of
before writing actual code. an algorithm
Pseudocode is best for logically designing Flowcharts are great for visualizing
algorithms and refining them before actual processes and presenting a clear picture of
coding. the flow, particularly to non-
programmers.

iii. Data structures vs. Control structures

Feature Data Structures Control Structures


Definition Ways of organizing, managing, and storing Constructs used to control the flow of
data for efficient access and modification. execution in a program.
Purpose to store and organize data in a logical way. To determine the order in which instructions
are executed.
Use in Used to manage and handle large datasets, Used to implement decision-making,
Programming optimize searching, sorting, etc. iteration, and function calls in algorithms.
Examples Arrays, Linked Lists, Stacks, Queues, Trees, If-else, For loop, While loop, Switch-case,
Hash Tables. Function calls.
Relation to Improves how data is stored and retrieved, Ensures the correct execution flow and
Code impacting memory and performance. handles loops, conditions, and recursion
Efficiency efficiently.

iv. Algorithm vs. Pseudocode

Feature Algorithm Pseudocode


Definition A step-by-step procedure or set of rules for A high-level, informal description of an
solving a problem or completing a task. algorithm using a mix of natural language
and programming-like syntax.

Class: XI Page 8 of 12 Computer Science (Chapter#2)


Purpose To provide a logical sequence to solve a To represent the algorithm in a way that’s
problem efficiently. easy to understand, often used as a blueprint
for coding.
Language Written in natural language, mathematical Written in a simplified form, similar to
notation, or diagrams, but doesn't follow any programming languages, but not language-
specific syntax. specific or executable.
Execution Cannot be executed directly on a computer; it Serves as a bridge between the algorithm
needs to be converted into a programming and code but is not directly executable.
language.
Goal To find the most efficient and optimal way to To describe the logic and flow of an
solve a problem. algorithm in a simplified, readable manner.
Example Sorting a list of numbers using step-by-step A pseudocode example might look like:
instructions like comparison, swapping, and 1. Input list
looping. 2. For each element, compare and sort
3. Output sorted list.

Q2: Write note on working of Bubble sort

Bubble Sort is a simple sorting algorithm that works by repeatedly stepping through the list, comparing
adjacent elements, and swapping them if they are in the wrong order. This process is repeated until the list is
sorted.

How it Works:

1. Compare Adjacent Elements: Starting from the beginning of the list, compare each pair of adjacent
elements.
2. Swap if Necessary: If the elements are in the wrong order (i.e., the first element is greater than the
second), swap them.
3. Repeat Passes: Continue this process for each pair of adjacent elements, moving through the list.
4. Reduce Range: After each pass, the largest unsorted element is placed at its correct position. Reduce the
range of the list to be sorted by one element after each pass.
5. Termination: Repeat the process until no more swaps are needed, indicating that the list is sorted.

Characteristics:

 Time Complexity: The algorithm needs to make many passes through the list, comparing and swapping
elements in each pass.
 Space Complexity: Bubble Sort only uses a small, fixed amount of extra space for temporary storage during
swaps, making it very space-efficient.
 Stable: Maintains the relative order of equal elements.

Bubble Sort is intuitive but inefficient for large lists due to its quadratic time complexity.

Q3: Write names of commonly used computational artifacts made during computational thinking.

Commonly used computational artifacts in computational thinking include:

1. Algorithms (e.g., sorting and searching algorithms)


2. Flowcharts (visual representation of algorithms)
Class: XI Page 9 of 12 Computer Science (Chapter#2)
3. Pseudocode (high-level description of algorithms)
4. Programs/Software (code written in various programming languages)
5. Simulations (models of real-world systems)
6. Spreadsheets (data organization and analysis)
7. Databases (structured data storage)
8. Websites (web applications and pages)
9. Digital Images (graphics and visual content)
10. Documentation (explanations and instructions related to computational processes)

Q4: Where we prefer to use binary search algorithm rather than linear search algorithm?

Binary Search is preferred over Linear Search in the following scenarios:

1. Sorted Data: Binary search is efficient for searching in sorted arrays or lists, as it relies on the order of
elements to reduce the search space quickly.
2. Large Data Sets: For large data sets, binary search is significantly faster due to its logarithmic time
complexity
3. Frequent Searches: When you need to perform multiple searches on a large, sorted data set, binary
search can save time with its efficient search mechanism.

Linear Search is used when:

 The data is unsorted.


 The list is short or searches are infrequent.

In summary, binary search is best when dealing with large, sorted data sets where efficient search performance
is crucial.

Q5: What are the advantages of using flowcharts?

Flowcharts offer several advantages:

1. Visual Clarity: They provide a clear, visual representation of the algorithm or process, making it easier
to understand and follow.
2. Simplifies Complex Processes: Flowcharts break down complex processes into manageable steps,
helping to identify and address potential issues.
3. Easy to Communicate: They facilitate communication and collaboration by providing a common visual
language that non-programmers and stakeholders can understand.
4. Error Detection: By mapping out processes visually, flowcharts help in spotting logical errors or
inefficiencies before implementation.
5. Documentation: They serve as useful documentation for understanding and maintaining algorithms or
processes over time.
6. Structured Approach: They help in organizing and structuring thoughts and processes in a systematic
manner.

Overall, flowcharts are valuable for planning, analyzing, and communicating processes or algorithms.

Give long answers to the following Extended Response Questions (ERQs).


Q 1. Determine the properties involved in computational thinking. (Given above)

Class: XI Page 10 of 12 Computer Science (Chapter#2)


Q 2. Sketch an algorithm that inputs length in inches and prints it in centimetres.

Algorithm: Inches to Centimeters Conversion


1. Start
2. Input: Read the length in inches (let's call it inches)
3. Calculate: Convert inches to centimeters using the formula: centimeters=inches×2.54
4. centimeters=inches×2.54
5. Output: Print the length in centimeters
6. End
Pseudocode:
Input: inches
Output: centimeters

// Step 1: Read the length in inches


Read inches
// Step 2: Convert inches to centimeters
centimeters = inches * 2.54
// Step 3: Print the result
Print "Length in centimeters: ", centimeters
End
Q4: Implement an algorithm to print multiplication table of a number in reverse order.

Algorithm: Reverse Multiplication Table


1. Start
2. Input: Read the number (let's call it num)
3. Input: Read the maximum multiplier (let's call it maxMultiplier)
4. Loop: Iterate from maxMultiplier down to 1
o Calculate: Compute the product of num and the current multiplier
o Output: Print the result in the format "num × multiplier = result"
5. End

Pseudocode:
Algorithm ReverseMultiplicationTable
Input: num, maxMultiplier
Output: Multiplication table in reverse order

// Step 1: Read the number and maximum multiplier


Read num
Read maxMultiplier

// Step 2: Loop from maxMultiplier down to 1


For i from maxMultiplier down to 1
// Calculate the product
result = num * i
// Print the multiplication result
Print num, " × ", i, " = ", result
End For
End
Q 4. Examine the uses of Flowcharts. (discussed above)

Q 5. A newly developed Algorithm needs to be tested. Argue about the reasons.

Testing a newly developed algorithm is crucial for several reasons:

1. Correctness: Reason: The primary goal of testing is to ensure that the algorithm produces the correct output for all
valid inputs. It helps verify that the logic and steps of the algorithm work as intended.
Class: XI Page 11 of 12 Computer Science (Chapter#2)
Example: If an algorithm is designed to sort a list, testing will confirm that the output is always sorted correctly for
various types of input.

2. Efficiency: Reason: Algorithms can often be implemented in various ways, some more efficient than others. Testing
allows developers to evaluate the time and space complexity (i.e., speed and memory usage) of the algorithm and see if
it performs optimally, especially on large datasets.

Example: A sorting algorithm should be tested on different data sizes to ensure it scales well and doesn't become too
slow or consume too much memory.

3. Edge Cases: Reason: Edge cases are situations where the input is unusual or extreme (e.g., empty input, very large
input). These cases can often cause unexpected behavior or failures, so testing ensures that the algorithm can handle all
possible inputs, including edge cases.

Example: Testing a search algorithm with an empty list, a list with one element, or a list with duplicate elements helps
ensure that the algorithm is robust.

4. Handling of Invalid Input: Reason: An algorithm should be tested to see how it handles invalid or unexpected inputs.
Proper error handling is important to prevent crashes or incorrect results.

Example: If the algorithm is designed to sort numbers, what happens if the input contains letters or special characters?
Testing helps to identify and manage such cases.

5. Performance Comparison: Reason: Testing allows the algorithm to be compared with existing algorithms in terms of
performance and resource utilization. This helps determine whether the new algorithm provides any advantages over
current solutions.

Example: If a new sorting algorithm is developed, it should be tested against known algorithms like QuickSort or
MergeSort to see if it offers any improvements in speed or memory usage.

6. Validation of Requirements: Reason: Testing ensures that the algorithm meets the specific requirements or goals set
at the beginning of development. It verifies that the algorithm performs the desired tasks and fulfills the problem's
needs.

Example: If an algorithm is designed to filter spam emails, testing ensures that it accurately distinguishes between spam
and non-spam emails as required.

7. Debugging and Error Detection: Reason: During testing, any logical errors, bugs, or inefficiencies in the algorithm can
be identified and fixed before deployment. Testing reveals flaws in the algorithm that might not be apparent during
development.
Line x total output
Example: Testing may reveal that an algorithm behaves #
unpredictably when processing a large input set, which could 1
indicate a memory overflow issue.
2 2 -
Activity 1: Complete the given trace table using the following 3 2 0
algorithm snippet. 5 2 2
5 2 4
1. Start
5 2 6
2. x=2
6 6
3. total=0
4. REPEAT Step 5 Three TIMES
5. total= total + x
6. Print (total)
7.End
Class: XI Page 12 of 12 Computer Science (Chapter#2)

You might also like