0% found this document useful (0 votes)
14 views55 pages

COMP102-Introduction-to-Algorithm-and-Pseudocode_161268

The document provides an introduction to algorithms and pseudocode, defining algorithms as finite sets of instructions for problem-solving and outlining key properties such as precision, finiteness, and effectiveness. It discusses how to analyze algorithm efficiency through time and space complexity, and offers guidelines for writing algorithms and pseudocode with examples. Additionally, it highlights the benefits of pseudocode in simplifying problem-solving and enhancing communication among team members.

Uploaded by

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

COMP102-Introduction-to-Algorithm-and-Pseudocode_161268

The document provides an introduction to algorithms and pseudocode, defining algorithms as finite sets of instructions for problem-solving and outlining key properties such as precision, finiteness, and effectiveness. It discusses how to analyze algorithm efficiency through time and space complexity, and offers guidelines for writing algorithms and pseudocode with examples. Additionally, it highlights the benefits of pseudocode in simplifying problem-solving and enhancing communication among team members.

Uploaded by

chriyanqamar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

Introduction to

Algorithm and
Pseudocode
Dr.Ifra AFZAL
ALGORITHM PSEUDOCODE.

PROPERTIES OF AN ALGORITHM PROPERTIES OF A PSEUDOCODE.

Contents:
HOW TO CHECK ALGORITHM
EFFICIENCY? HOW TO WRITE PSEUDOCODE

WRITING THE ALGORITHM EXERCISE

EXERCISE ALGORITHM VS. PSEUDOCODE


Algorithm
An algorithm is a finite set of well-defined
instructions that are executed in a specific order
to solve a problem or perform a task.
Algorithms are used in programming,
mathematics, and various fields to automate
problem-solving and decision-making processes.

For example, a recipe for baking a cake is


analogous to an algorithm because it provides a
step-by-step guide to achieve a result.

25/11/20 Introduction to Algorithm and


3
24 Pseudocode
Properties of an
Algorithm
Key Properties of an Algorithm
1. Precise and Unambiguous 4. Independent
Each instruction should be clear, with no An algorithm is not tied to any
room for multiple interpretations. This programming language. It should be
ensures that every step is understandable adaptable and can be implemented in
and implementable. any language or system.

2. Finite 5. Input
An algorithm must terminate after a finite Algorithms take zero, one, or more
number of steps. It should not run inputs, such as numbers, strings, or
indefinitely or fall into an infinite loop. other data.

3. Effectiveness 6. Output
The instructions in the algorithm must be The algorithm must produce at least
simple, basic, and capable of being one output (a result or solution).
executed within a finite amount of time
and resources. 7. Deterministic
The result of each step must depend
only on the input and not on random
choices.
5
How to Check
Algorithm Efficiency?

6
Two Key Aspects of Efficiency

1. TIME
COMPLEXITY

2. SPACE
COMPLEXITY

• Algorithm efficiency measures how well an algorithm performs in terms of time


and space as the size of the input increases. Evaluating efficiency ensures that
an algorithm is not only correct but also optimal for practical use.
1. Time Complexity

•Measures the amount of time an algorithm takes to complete relative to the


input size.

•Focuses on the number of steps or operations performed.

•Commonly expressed in Big-O notation, such as

8
Time Complexity (Asymptotic notation )
1. Best Case:
• Minimum resources needed
• lower bound of an algorithm
• (Big-Omega (Ω))

2. Average Case:
• Expected resources needed
• lower and upper bounds have the same time complexity
• (Theta (θ))

3. Worst Case:
• Maximum resources needed
• lower bound of an algorithm
• (Big-oh (O))

9
Space Complexity
Measures the amount of memory required to execute an algorithm, including:
1.Input Space: Space required to store input data.
2.Auxiliary Space: Additional memory for temporary variables, data structures, etc.
3.Output Space: Memory required for the output.

• Common Scenarios:
• An algorithm with space complexity requires a fixed amount of memory.
• Algorithms that create and use large data structures, like hash tables or recursion
stacks, may have or higher space complexity.
• Example:
In Merge Sort, space complexity is because temporary arrays are created for merging.

10
Methods to Analyze Efficiency
1. Asymptotic Analysis
• (Big-Omega (Ω))
• (Theta (θ))
• (Big-oh (O))

2. Empirical Testing
• Measure the time and memory usage of the algorithm by running it on
actual data.

11
Writing the Algorithm
Step 1: Start.

Step 2: Define and initialize variables (if required).

Step 3: Write the logic for the problem.

Step 4: Produce the output.

Step 5: End.

12
Example 1

Problem: Add two numbers and display the result.

1. Start.

2. Input two numbers, a and b.

3. Calculate the sum, sum = a + b.

4. Output sum.

5. End.

13
Example 2
Problem: Check if a given number is even or odd.
Algorithm
1. Start
2. Input a number.
3. Use the modulus operator (%) to find the remainder when
the number is divided by 2.
4. If the remainder is 0, the number is even.
5. If the remainder is 1, the number is odd.
6. End.
Example 3
Problem: Find the Largest Number in a List
Algorithm
1. Start.
2. Input a list of numbers.
3. Initialize max to the first element of the list.
4. For each number in the list, do the following:
• Compare it with max.
• If it is greater than max, update max.
5. Output max.
6. End.
Example 4

Problem: Calculate the factorial of a given


number N.
Example 4
Problem: Calculate the factorial of a given
number n.
Algorithm

1. Start
2. Initialize a variable result to 1
3. Input a number n
4. For i ranging from n to 1 (inclusive), multiply
result by i
5. Return result
6. End.
Problem: Count the number of vowels in a
given string.
Example 5
Problem: Count the number of vowels (a, e, i, o, u) in a
given string.
Algorithm
1. Start.
2. Input a string.
3. Initialize a variable vowel_count to 0.
4. For each character in string, do:
• If the character is a vowel (a, e, i, o, u)
• increment vowel_count.
5. Output vowel_count.
6. End.
Problem: Find the sum of all numbers in a
given list.
Example 6
Problem: Find the sum of all numbers in a given list.
Algorithm
1. Start.
2. Input the list of numbers.
3. Initialize a variable sum to 0.
4. For each number in the list:
• Add it to sum.
5. Output sum.
6. End.
Problem: Check if a given string is a
palindrome (reads the same forward and
backward)
(Level, Radar, rotator etc.).
Example 7
Problem: Check if a given string is a palindrome.
Algorithm
1. Start.
2. Read the input string 𝑆.
3. Reverse the string 𝑆 and store it in 𝑅.
4. Compare S with R.
5. If 𝑆=𝑅, print "The string is a palindrome.“
6. Otherwise, print "The string is not a palindrome.“
7. Stop.
Problem: Count the number of words in a
given sentence.
Example 8
Problem: Count the number of words in a given sentence.
Algorithm
1. Start.
2. Input a sentence, sentence.
3. Split sentence into words using spaces as separators.
4. Count the number of words in the list.
5. Output the word count.
6. End.
Problem: To Find the Power of a Number.
Compute a^b (a raised to the power b).
Example 9
Problem: Compute x^n (a raised to the power b).
Algorithm
1. Start.
2. Input the base x and exponent n.
3. Initialize a variable result to 1.
4. Repeat n times:
• result = result × x.
5. output result.
6. Stop.
Problem: Guess the Number
Game

Problem Statement
Design an algorithm for a simple game where the teacher (I) picks a random number, and
(You) students have to guess it. The algorithm will guide the process of providing hints
such as "too high" or "too low" until the correct guess is made.
Example 10
2. The teacher secretly selects a number 𝑁 (e.g.,
1. Start.

1≤𝑁≤100).

4. Prompt the student to make a guess 𝐺.


3. Initialize the attempt counter to 0.

6. Compare 𝐺 with 𝑁:
5. Increment the attempt counter.

• If 𝐺=𝑁, print "Correct! You guessed it in X

• If 𝐺>𝑁, print "Too high!" and go to Step 4.


attempts." and stop.

• If 𝐺<𝑁, print "Too low!" and go to Step 4.


7. Stop.
What is Pseudocode?
What is Pseudocode
Pseudocode is a high-level, informal way of
describing the logic of a program or algorithm. It uses
plain language combined with programming concepts
to outline the steps needed to solve a problem. While
it resembles programming code, it does not follow the
strict syntax of any specific programming language,
making it easier to understand.

20XX presentation title 31


Purpose of Pseudocode
1. Simplify Problem-Solving: Helps in planning and organizing
thoughts before writing actual code.

2. Language Independent: Focuses on logic without worrying about


syntax errors of a specific programming language.

3. Communication: Used to communicate ideas among team


members, especially those who may not know programming.

4. Education: Helps beginners understand programming concepts


without the complexity of code syntax.

20XX presentation title 32


Characteristics of Good Pseudocode
1. Readable: Easy to understand for anyone familiar with
programming concepts.

2. Precise: Clearly defines the logic and flow of the algorithm.

3. Structured: Uses numbering, and consistent style to represent


hierarchy and steps.

4. Language Neutral: Avoids the syntax of any specific programming


language.
5. Comprehensive: Covers all aspects of the logic, including edge
cases and error handling.

20XX presentation title 33


Benefits of Pseudocode

Focus on Logic: Error Reduction: Collaboration Flexibility:


• By removing • Planning with • Acts as a • Easy to modify
language-specific pseudocode common and adapt
syntax, it reduces errors language compared to
encourages when translating between written code.
focusing on the into code. technical and
actual problem- non-technical
solving process. stakeholders.

20XX presentation title 34


Structure of Pseudocode
Pseudocode generally follows these components:

1. Input: Define the data or values that will be provided as input to the
algorithm.

2. Processing: Describe the procedural framework or logical reasoning


needed to process the input.

3. Output: State what the result will be.

20XX presentation title 35


Pseudocode Keywords
• Common keywords used in pseudocode are:
Keyword Purpose

BEGIN / END Marks the start and end of the pseudocode.

INPUT Specifies data or input to be provided.

OUTPUT Specifies the result or output of the algorithm.

IF, ELSE Conditional statements.

WHILE, FOR Looping constructs.

RETURN Provides the result of a function or exits.

READ / WRITE Used to simulate reading/writing data.


20XX presentation title 36
Example 1
Problem: Add two numbers and display the result.
Pseudocode:

START
INPUT num1
INPUT num2
sum ← num1 + num2
OUTPUT sum
END

37
Example 2
Problem: Check if a given number is even or odd.
Pseudocode:

START
INPUT num
IF num MOD 2 == 0
OUTPUT "Even"
ELSE
OUTPUT "Odd"
ENDIF
END
Example 3
Problem: Find the Largest Number in a List
Pseudocode:
START
INPUT list of numbers
SET largest ← list[0] // Initialize with the first number
FOR each number in list DO
IF number > largest THEN
SET largest ← number
ENDIF
ENDFOR
OUTPUT largest
END
Example 4

Problem: Calculate the factorial of a given


number N.
Example 4
Problem: Calculate the factorial of a given
number n.
Pseudocode:

START
INPUT N
SET factorial ← 1
FOR i from 1 to N DO
factorial ← factorial * i
ENDFOR
OUTPUT factorial
END
Problem: Count the number of vowels in a
given string.
Example 5
Problem: Count the number of vowels (a, e, i, o, u) in a
given string.
Pseudocode:

START
INPUT string
SET count ← 0
FOR each character in string DO
IF character is 'a' OR 'e' OR 'i' OR 'o' OR 'u' OR 'A' OR 'E' OR
'I' OR 'O' OR 'U' THEN
INCREMENT count by 1
ENDIF
ENDFOR
OUTPUT count
END
Problem: Find the sum of all numbers in a
given list.
Example 6
Problem: Find the sum of all numbers in a given list.
Pseudocode:
START
INPUT list of numbers
SET sum ← 0
FOR each number in list DO
sum ← sum + number
ENDFOR
OUTPUT sum
END
Problem: Check if a given string is a
palindrome (reads the same forward and
backward)
(Level, Radar, rotator etc.).
Example 7
Problem: Check if a given string is a palindrome.
Pseudocode:

START
INPUT string
SET start_index ← 0
SET end_index ← length of string - 1
WHILE start_index < end_index DO
IF string[start_index] ≠ string[end_index] THEN
OUTPUT "Not a Palindrome"
EXIT
ENDIF
INCREMENT start_index by 1
DECREMENT end_index by 1
ENDWHILE
OUTPUT "Palindrome"
END
Problem: Count the number of words in a
given sentence.
Example 8
Problem: Count the number of words in a given sentence.
Pseudocode:

START
INPUT sentence
SET word_count ← 0
SPLIT sentence into words using spaces as delimiters
FOR each word in the list of words DO
INCREMENT word_count by 1
ENDFOR
OUTPUT word_count
END
Problem: To Find the Power of a Number.
Compute a^b (a raised to the power b).
Example 9
Problem: Compute x^n (a raised to the power b).
Pseudocode:
START
INPUT base (a)
INPUT exponent (b)
SET result ← 1
FOR i FROM 1 TO b DO
result ← result * a
ENDFOR
OUTPUT result
END
Problem: Guess the Number
Game

Problem Statement
Design an algorithm for a simple game where the teacher (I) picks a random number, and
(You) students have to guess it. The algorithm will guide the process of providing hints
such as "too high" or "too low" until the correct guess is made.
Example 10
START
SET N ← a randomly chosen number between 1 and 100
SET attempt_counter ← 0
WHILE TRUE DO
PROMPT "Enter your guess:" and INPUT G
INCREMENT attempt_counter by 1
IF G = N THEN
OUTPUT "Correct! You guessed it in " + attempt_counter + "
attempts."
BREAK
ELSE IF G > N THEN
OUTPUT "Too high!"
ELSE
OUTPUT "Too low!"
ENDIF
ENDWHILE
END
Algorithm vs. Pseudocode
Feature Algorithm Pseudocode

Formality More formal, uses structured steps. Informal, uses plain language.

Syntax Doesn't resemble programming code. Resembles programming logic.

Highly flexible, focuses on


Flexibility Less flexible, follows strict structure.
readability.

Usage Suitable for theoretical descriptions. Bridges theory and implementation.

20XX presentation title 54


Thank You

You might also like