0% found this document useful (0 votes)
2 views22 pages

Algorithm

This chapter introduces algorithms as step-by-step instructions for problem-solving, highlighting their characteristics, importance, and limitations. It covers constructs like sequence, selection, and iteration, as well as flowcharting and types of loops, including for, while, and do-while loops. Additionally, it discusses decomposition, abstraction, and linear search, providing examples and objective questions to reinforce understanding.

Uploaded by

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

Algorithm

This chapter introduces algorithms as step-by-step instructions for problem-solving, highlighting their characteristics, importance, and limitations. It covers constructs like sequence, selection, and iteration, as well as flowcharting and types of loops, including for, while, and do-while loops. Additionally, it discusses decomposition, abstraction, and linear search, providing examples and objective questions to reinforce understanding.

Uploaded by

s4060678
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Chapter: Introduction to Algorithm

1. What is an Algorithm?

An algorithm is a step-by-step set of instructions designed to perform a specific task or solve a problem.
Think of it as a recipe: just like a recipe outlines steps to prepare a dish, an algorithm provides steps to
achieve a desired outcome. Algorithms can be used in computers, everyday life, and various problem-
solving activities.

Example:

If you want to find the shortest route to a destination, your navigation app uses an algorithm to
calculate it for you.

2. Characteristics/Properties of an Algorithm

An algorithm has the following characteristics:

1. Input: It takes zero or more inputs (e.g., numbers, data).

2. Output: It provides at least one output (e.g., a solution, a result).

3. Finiteness: It must end after a finite number of steps.


4. Definiteness: Each step of the algorithm must be clear and unambiguous.

5. Effectiveness: All operations in the algorithm must be simple enough to be performed, in theory, by
hand.

---

3. Importance of Algorithms

Algorithms play a critical role in our daily lives and technology:

Efficiency: They allow us to solve problems in the shortest possible time.

Automation: They help computers perform complex tasks without human intervention.

Problem-solving: They offer systematic solutions for a variety of problems, from basic arithmetic to
artificial intelligence.

---
4. Disadvantages of Algorithms

Despite their importance, algorithms have some limitations:

1. Complexity: Some algorithms can be challenging to design and understand.

2. Time Consumption: Designing the right algorithm for a problem can take time.

3. Rigidity: They work only for the problem they are designed for; modifications may require redesigning
the algorithm.

---

5. Flowchart Symbols and Flowcharting

A flowchart is a visual representation of an algorithm using symbols. It makes it easier to understand the
steps of the algorithm.

Common Flowchart Symbols:

1. Oval: Represents the start or end of a process.


2. Rectangle: Represents a process or operation.

3. Diamond: Represents a decision point.

4. Arrow: Represents the flow of the process.

---

6. The Three Constructs of an Algorithm

Algorithms are built using three basic constructs:

1. Sequence: Executing steps one after another in a specific order.

Example: Making tea involves heating water, adding tea leaves, and pouring it into a cup in a sequence.
2. Selection (Decision-making): Choosing between two or more options based on a condition.

Example: If it rains, carry an umbrella; otherwise, don’t.

3. Iteration (Looping): Repeating a step or set of steps until a condition is met.

Example: Counting numbers from 1 to 10 by repeating the step of adding 1.

Types of Loops

Loops are tools in programming that repeat actions. There are different types of loops depending on
what you need to do. Let’s break them down simply:

---

1. For Loop

A for loop is used when you know how many times you want to repeat something.

Example:

Imagine counting from 1 to 5.

for i in range(1, 6): # Start at 1, end at 5


print(i)

What happens? The program prints:

When to use it?

Counting numbers.

Going through a list, like names or items in a shopping cart.

---

2. While Loop

A while loop keeps running as long as a condition is true.

Example:
Imagine filling a bucket until it’s full.

water = 0

while water < 5: # Keep adding water until it reaches 5

print("Filling water...")

water += 1

What happens? It prints:

Filling water...

Filling water...

Filling water...

Filling water...

Filling water...

When to use it?

When you don’t know how many times the action will repeat, but you have a stopping condition.

Example: Asking a user for correct input until they enter the right answer.

---
3. Do-While Loop

A do-while loop is like a while loop, but it always runs at least once, even if the condition is false. (This
loop isn’t in Python but exists in other languages like C++ and Java.)

Example in Real Life:

Imagine entering a room and checking if the lights are off:

1. You always look first (action happens once).

2. If the lights are still on, you keep checking.

---

4. Nested Loops

A nested loop is a loop inside another loop.

Example:

Imagine printing a list of rows and columns like in a table:

for row in range(1, 3): # Outer loop


for col in range(1, 4): # Inner loop

print(f"Row {row}, Column {col}")

What happens? It prints:

Row 1, Column 1

Row 1, Column 2

Row 1, Column 3

Row 2, Column 1

Row 2, Column 2

Row 2, Column 3

When to use it?

Working with grids or tables.

Solving problems with multiple levels, like a schedule for each day and hour.

---

5. Infinite Loop

An infinite loop keeps going forever because the stopping condition is never met.
Example:

while True:

print("This will run forever!")

When to use it?

Rarely. Useful for things like running a program that listens for user commands until they quit.

---

Summary Table

---

Loops help automate repetitive tasks and make programs simpler and faster!
---

7. Demonstrating Sequence, Selection, and Iteration

Everyday Life Examples:

1. Sequence: Brushing your teeth.

Steps: Take toothpaste → Apply on the brush → Brush your teeth → Rinse your mouth.

2. Selection: Deciding what to wear.

If the weather is cold, wear a jacket; if not, wear a T-shirt.

3. Iteration: Filling a water tank.

Repeat filling the tank until it is full.


Programming Examples:

1. Sequence: Printing a message on the screen.

print("Hello!")

print("Welcome to algorithms!")

2. Selection: Checking if a number is even or odd.

number = 5

if number % 2 == 0:

print("Even")

else:

print("Odd")

3. Iteration: Printing numbers from 1 to 5.

for i in range(1, 6):

print(i)
---

8. What is Decomposition and Abstraction?

1. Decomposition: Breaking a large problem into smaller, manageable parts.

Example: Planning a birthday party involves smaller tasks like sending invitations, buying a cake, and
setting up decorations.

2. Abstraction: Focusing only on the important details of a problem and ignoring unnecessary ones.

Example: When driving, you care about the route (important) but not the detailed workings of the GPS
system (unimportant).

---

9. What is Linear Search?

A linear search is a simple searching technique where you go through a list one item at a time to find a
specific element. It is straightforward but not the most efficient for large datasets.
Everyday Life Example:

Searching for a contact in your phone:

1. Open your contact list.

2. Scroll through one name at a time until you find the desired contact.

---

10. How Does Linear Search Work?

Here’s how a linear search algorithm works:

1. Start from the first item in the list.

2. Compare it with the target value.

3. If it matches, the search ends.


4. If it doesn’t, move to the next item and repeat steps 2–4.

5. If you reach the end of the list and the target is not found, conclude that it’s not present.

Example in Python:

def linear_search(arr, target):

for i in range(len(arr)):

if arr[i] == target:

return f"Found at index {i}"

return "Not found"

# Example usage

numbers = [10, 20, 30, 40, 50]

print(linear_search(numbers, 30)) # Output: Found at index 2

---

This chapter provides a strong foundation for understanding algorithms and their role in solving
problems systematically.
Objective Questions on Algorithm

1. What is an algorithm?

A. A computer program

B. A step-by-step solution to a problem

C. A programming language

D. A type of data structure

Answer: B

2. Which of the following is NOT a property of an algorithm?

A. Finiteness

B. Definiteness

C. Multiplicity

D. Effectiveness

Answer: C

3. What is the first step in writing an algorithm?

A. Writing code

B. Understanding the problem

C. Testing the solution

D. Debugging

Answer: B
4. Which construct in an algorithm deals with decision-making?

A. Sequence

B. Selection

C. Iteration

D. Input

Answer: B

5. An algorithm is said to be finite if it:

A. Uses loops

B. Has multiple outputs

C. Terminates after a finite number of steps

D. Accepts user input

Answer: C

6. What is a flowchart used for in algorithms?

A. Debugging code

B. Visually representing an algorithm

C. Measuring the speed of an algorithm

D. Writing a program

Answer: B
7. Which flowchart symbol represents a decision?

A. Rectangle

B. Oval

C. Diamond

D. Circle

Answer: C

8. In which construct does an algorithm repeat steps?

A. Sequence

B. Selection

C. Iteration

D. Input

Answer: C

9. The output of an algorithm must be:

A. A number

B. Text

C. Meaningful and correct

D. A program

Answer: C
10. Which type of algorithm searches through a list one item at a time?

A. Binary Search

B. Linear Search

C. Depth-First Search

D. Quick Sort

Answer: B

11. Which of the following best describes abstraction in algorithms?

A. Ignoring unnecessary details

B. Breaking a problem into parts

C. Focusing on the input

D. Writing complex algorithms

Answer: A

12. Decomposition in algorithms means:

A. Combining smaller tasks

B. Breaking a problem into smaller parts

C. Removing errors from code

D. Ignoring unnecessary steps

Answer: B

13. What is the purpose of a loop in an algorithm?


A. To repeat tasks

B. To make decisions

C. To perform arithmetic operations

D. To create flowcharts

Answer: A

14. What type of loop always runs at least once?

A. For loop

B. While loop

C. Do-while loop

D. Nested loop

Answer: C

15. Which of the following is an advantage of algorithms?

A. They are language-specific

B. They help solve problems systematically

C. They increase program size

D. They reduce accuracy

Answer: B

16. What does a linear search algorithm do if it doesn’t find the target value?

A. Stops immediately
B. Continues searching indefinitely

C. Checks all elements and returns “not found”

D. Throws an error

Answer: C

17. Which of the following is a disadvantage of algorithms?

A. They are complex to understand

B. They are only used in programming

C. They require inputs

D. They solve problems systematically

Answer: A

18. What does the term "iteration" mean in an algorithm?

A. Breaking a problem into parts

B. Ignoring unnecessary steps

C. Repeating steps until a condition is met

D. Choosing between two options

Answer: C

19. Which of the following is an example of selection in an algorithm?

A. Counting numbers from 1 to 10

B. If it is raining, take an umbrella


C. Adding two numbers

D. Finding the largest number in a list

Answer: B

20. What is the result of an algorithm that does not terminate?

A. A correct output

B. A runtime error

C. An infinite loop

D. A logical error

Answer: C

You might also like