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

Practical Programming -L02

The document provides an overview of algorithms, including their definition, characteristics, and types, as well as practical exercises for creating and testing algorithms. It covers the historical context of algorithms and their applications in real life, such as in search engines and GPS navigation. Additionally, it discusses specific algorithms for searching and sorting, along with examples and steps for implementation.

Uploaded by

Jaafar Abbakar
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)
4 views

Practical Programming -L02

The document provides an overview of algorithms, including their definition, characteristics, and types, as well as practical exercises for creating and testing algorithms. It covers the historical context of algorithms and their applications in real life, such as in search engines and GPS navigation. Additionally, it discusses specific algorithms for searching and sorting, along with examples and steps for implementation.

Uploaded by

Jaafar Abbakar
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/ 25

University of Juba

Programming with C++


Practical Training
Lecture 2: Algorithms
Overview
• Introduction to Algorithms
• Characteristics of a Good Algorithm
• Variables and Constants in Algorithms
• Arithmetic Expressions
• Creating and Testing Algorithms
• Expressing Algorithms
• Types of Algorithms
• Searching and Sorting Algorithms
• Practical Exercises
1. Introduction to Algorithms
• Historical Context:
• The term "algorithm" comes from the 9th-century Persian mathematician
Muhammad ibn Musa al-Khwarizmi, who introduced systematic methods
for solving mathematical problems.
• Modern Contributions:
• Ada Lovelace: Wrote the first
algorithm for Charles Babbage's
Analytical Engine, making her
the first computer programmer.
• Alan Turing: Developed the
concept of the Turing machine, a
foundational idea in computer
science.
What is an Algorithm?
• An algorithm is a step-by-step procedure or a set of rules to
solve a specific problem or perform a task.
• Examples in Real Life:
• Google Search: Algorithms rank web pages based on relevance.
• GPS Navigation: Algorithms find the shortest path between two
points.
• Social Media Feeds: Algorithms decide what content shows to
you.
How do algorithms work?
Working of algorithms is very easy, and it will be much easier to
understand with the help of the image shown:
2. Characteristics of a Good Algorithm
Input: An algorithm must have clearly defined inputs.
Output: It must produce at least one output.
Clear Instructions: Steps must be unambiguous and easy to follow.
Finiteness: The algorithm must terminate after a finite number of
steps.
Effectiveness (Workable): It should be simple and executable with
available resources.
Language Independence: The algorithm should work regardless of
the programming language used.
2. Characteristics of a Good Algorithm
3. Variables and Constants in Algorithms
Variables:
• A named storage location that holds a value at a specific point in
time.
• The value of a variable remains constant until it is explicitly
changed by a step in the algorithm.
• Each variable has a unique name within the algorithm.
• For example, the variable x might represent an input value,
while the variable result might represent an output value.
• When converting an algorithm into a program, a variable
becomes a location in RAM (Random Access Memory).
3. Variables and Constants in Algorithms
Constants:
is a fixed value that cannot be changed, such as numbers (e.g., 2, -
38, 325.3) or characters (e.g., 'a', 'Z’).
• Constants can be used as immediate values for variables.
• For example, the variable x might take the constant value 2 at
one point and later change to 3.
• Character constants are usually written within single quotes
(e.g., 'a', 'Z'), while string constants are written within double
quotes (e.g., "Hello", "result").
• Numeric constants do not need quotes because they cannot be
confused with variable names.
4. Arithmetic Expressions
• An arithmetic expression is a logically correct sequence of
variables, constants, arithmetic operations, and parentheses.
• For example, the expression x * (y - 10) contains the
variables x and y, the constant 10, and the operations of
multiplication and subtraction.
• Operator Precedence:
• Parentheses () have the highest precedence.
• Multiplication and division are performed before
addition and subtraction.
5. Creating and Testing Algorithms
Steps to Create an Algorithm:
• Identify the Problem: What problem are you trying to solve?
• Define Constraints: What limitations or rules must you follow?
• Determine Inputs and Outputs: What data will the algorithm
use, and what should it produce?
• Design the Algorithm: Write the steps in natural language or a
flowchart or a pseudo-code.
• Test the Algorithm: Run it with sample inputs to ensure it
works correctly.
Example: Algorithm to find the sum of two numbers
• Problem: Sum of two numbers.
• Constraints: Inputs must be integers.
• Input: a, b.
• Output: sum.
• Algorithm: Expressing in:
I. natural language or
II. flowchart or
III. pseudo-code.
• Testing: Testing this algorithm in C++.
6. Expressing Algorithms
I. Natural Language: Easy to understand but can be ambiguous.
Example: “Algorithm to find the sum of two numbers.”
1. Start
2. Read the value of a and b.
3. sum = a + b.
4. Print the value of sum.
5. Stop.
6. Expressing Algorithms
II. Flowcharts: A graphical representation of steps.
Example: “Flowchart to find the sum of two numbers”
6. Expressing Algorithms
III. Pseudo-Code: A mix of natural language and programming
syntax.
Example: “Pseudo-Code to find the sum of two numbers”
START
INPUT a, b
sum = a + b
OUTPUT sum
END
7. Types of Algorithms
• Here are some common types of algorithms with examples:
Type Description Example

Greedy Algorithm Chooses the best option at each step without considering Finding the shortest path in a
the overall result. graph.

Brute Force Tries all possible solutions to find the best one. Cracking a password by trying
all combinations.

Recursive Algorithm Solves a problem by breaking it into smaller instances of Calculating factorial or
the same problem. Fibonacci numbers.

Divide and Conquer Breaks a problem into smaller sub-problems, solves Merge Sort, Quick Sort.
them, and combines results.

Backtracking Tries different solutions and abandons them if they don’t Solving Sudoku or the N-
work. Queens problem.

Hashing Algorithm Maps data of any size to a fixed-size value (hash). Password storage, data
retrieval.

Searching Algorithm Finds an element in a data structure. Binary Search, Linear Search.
8. Searching and Sorting Algorithms
Searching Algorithms
• Linear Search: Sequentially checks each element in a list.
• Time Complexity: O(n).
• Best for: Small datasets.
• Binary Search: Efficient for sorted lists.
• Time Complexity: O(log n).
• Best for: Large, sorted datasets.
8. Searching and Sorting Algorithms
Sorting Algorithms
• Bubble Sort: Simple but inefficient for large datasets.
• Time Complexity: O(n²).
• Merge Sort: Efficient and stable.
• Time Complexity: O(n log n).
• Quick Sort: Fast and in-place.
• Time Complexity: O(n log n) on average.
9. Summary
• Key Takeaways:
• Algorithms are step-by-step procedures to solve
problems.
• They must be clear, finite, and produce the correct
output.
• Algorithms can be expressed in natural language,
flowcharts, or pseudo-code.
• Next Steps:
• Practice creating algorithms for different problems.
• Learn how to implement algorithms in C++ or other
programming languages.
10. Q&A and Discussion
11. Practical Exercises
1. Find the Maximum Number in a List:
• Write an algorithm to find the largest number in a list of integers.
• Test it with the following list: [3, 7, 2, 9, 4].
2. Calculate the Average of Numbers:
• Write an algorithm to calculate the average of a list of numbers.
• Test it with the following list: [10, 20, 30, 40, 50].
3. Sort a List of Numbers:
• Write an algorithm to sort a list of numbers in ascending order.
• Test it with the following list: [5, 3, 8, 1, 2].
Interactive Example 1
Problem: Find the maximum number in a list.
Algorithm:
1. Start
2. Read the list of numbers.
3. Set the first number as the maximum.
4. Compare each number with the current maximum.
5. If a number is greater, update the maximum.
6. Repeat until the end of the list.
7. Print the maximum number.
8. Stop.
Interactive Example 2
Problem: Calculate the Average of Numbers.
Algorithm:
1. Input: A list of numbers, numbers = [n1, n2, n3, ……,nk].
2. Steps:
• Initialize a variable total_sum to 0.
• Initialize a variable count to 0.
• Iterate through each number in the list:
• Add the current number to total_sum.
• Increment count by 1.
• Calculate the average by dividing total_sum by count
• Return the average.
3. Output: The average of the numbers in the list.
Interactive Example 3
Problem: Write an algorithm to sort a list of numbers in ascending order.
Algorithm:
a. Input: A list of numbers, numbers = [n1, n2, n3, ……,nk].
b. Steps:
1. Start with the first element of the list.
2. Compare the current element with the next element.
3. If the current element is greater than the next element, swap them.
4. Move to the next element and repeat step 2-3 until the end of list.
5. Repeat the entire process for the list until no swaps are needed.
6. Return the sorted list
c. Output: Sorted list.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy