Table of Contents

    Algorithm

    Programming Fundamentals

    Algorithm

    Learn what an algorithm is, why algorithms are important in programming, how to write algorithms, and how algorithms help solve problems step by step before writing actual code.

    What is an Algorithm?

    An algorithm is a step-by-step procedure used to solve a problem or complete a specific task. In programming, an algorithm describes the logical steps that a computer program should follow to produce the correct output.

    In simple words, an algorithm is a clear plan for solving a problem. Before writing code, programmers often create an algorithm to understand what needs to be done, what input is required, what processing is needed, and what output should be produced.

    An algorithm is a clear, finite, and logical set of steps used to solve a problem.

    A program is written in a programming language, but an algorithm is language-independent. This means the same algorithm can be converted into Java, Python, C, C++, JavaScript, PHP, C#, or any other programming language.

    Easy Real-Life Example

    Algorithm as a Recipe

    Think of making a cup of tea. You follow steps such as boiling water, adding tea leaves, adding milk, adding sugar, and serving it. These steps form an algorithm because they describe how to complete a task in a proper order.

    Tea-Making Algorithm
    Boil Water Add Tea Add Milk Add Sugar Serve

    In programming, the same idea applies. A programmer writes a series of logical steps so that the computer can solve the problem correctly.

    Why Do We Need Algorithms?

    Algorithms are needed because computers cannot solve problems automatically without instructions. A computer follows the steps given by the programmer. If the steps are correct, the output will be correct. If the steps are wrong, the output may be wrong.

    Importance of Algorithms

    • Algorithms help solve problems in a structured way.
    • They help programmers plan before coding.
    • They make logic easier to understand.
    • They reduce mistakes during programming.
    • They help convert real-world problems into computer instructions.
    • They make debugging easier.
    • They help compare different solutions to choose the best one.
    • They improve program efficiency and performance.
    • They are useful in exams, interviews, assignments, and real projects.

    Characteristics of a Good Algorithm

    A good algorithm should be clear, finite, correct, and effective. If an algorithm is confusing or incomplete, it becomes difficult to convert it into code.

    1

    Clear and Unambiguous

    Every step should have only one meaning.

    Each instruction in an algorithm should be simple and clear. A programmer should not be confused about what the step means.

    2

    Finite

    The algorithm must end after a limited number of steps.

    An algorithm should not run forever. It must have a definite stopping point.

    3

    Input

    It may accept zero or more inputs.

    Input is the data given to the algorithm. For example, to add two numbers, the two numbers are inputs.

    4

    Output

    It must produce at least one output.

    Output is the result produced by the algorithm. For example, the sum of two numbers is the output.

    5

    Effective

    Every step should be practical and executable.

    The steps should be possible to perform using available operations, logic, and resources.

    6

    Correct

    It should solve the given problem properly.

    A correct algorithm produces the expected output for valid input values.

    Basic Structure of an Algorithm

    Most beginner algorithms follow the Input, Process, Output model. First, the algorithm accepts input, then processes the input, and finally produces output.

    Algorithm Structure
    Input Process Output

    For example, in a program to calculate total price, the price and quantity are inputs, multiplication is the process, and total price is the output.

    Algorithm vs Program

    An algorithm and a program are closely related, but they are not the same. An algorithm is the plan, while a program is the implementation of that plan in a programming language.

    Algorithm Program
    Step-by-step logical solution. Code written in a programming language.
    Language-independent. Language-dependent.
    Written before coding. Written after planning the logic.
    Example: Add two numbers and display result. Example: Java, Python, or C code for adding two numbers.

    Algorithm vs Pseudocode vs Flowchart

    Algorithms can be represented in different ways. The most common ways are natural language steps, pseudocode, and flowcharts.

    Concept Meaning Example Use
    Algorithm Step-by-step method to solve a problem. Planning the solution.
    Pseudocode English-like code structure used to describe an algorithm. Writing logic before real code.
    Flowchart Visual diagram showing the flow of an algorithm. Understanding logic visually.

    Steps to Write an Algorithm

    To write a good algorithm, students should understand the problem first and then write the solution step by step.

    Algorithm Writing Steps

    • Read the problem statement carefully.
    • Identify the input values.
    • Identify the expected output.
    • Find the formula or logic required.
    • Write the steps in correct order.
    • Make sure each step is clear.
    • Check whether the algorithm stops after finite steps.
    • Test the algorithm using sample values.
    • Convert the algorithm into pseudocode or code.

    Example 1: Algorithm to Add Two Numbers

    Problem Statement

    Write an algorithm to add two numbers and display the result.

    Algorithm

    Steps

    • Start.
    • Take the first number.
    • Take the second number.
    • Add both numbers.
    • Store the result in a variable named sum.
    • Display the sum.
    • End.

    Pseudocode

    START
    INPUT number1
    INPUT number2
    SET sum = number1 + number2
    DISPLAY sum
    END

    Java Code

    public class Main {
        public static void main(String[] args) {
            int number1 = 10;
            int number2 = 20;
    
            int sum = number1 + number2;
    
            System.out.println("Sum: " + sum);
        }
    }

    Output

    Sum: 30

    Example 2: Algorithm to Check Even or Odd

    Problem Statement

    Write an algorithm to check whether a number is even or odd.

    Algorithm

    Steps

    • Start.
    • Take a number as input.
    • Divide the number by 2 and check the remainder.
    • If the remainder is 0, display “Even”.
    • Otherwise, display “Odd”.
    • End.

    Pseudocode

    START
    INPUT number
    IF number MOD 2 == 0 THEN
        DISPLAY "Even"
    ELSE
        DISPLAY "Odd"
    END IF
    END

    Java Code

    public class Main {
        public static void main(String[] args) {
            int number = 8;
    
            if (number % 2 == 0) {
                System.out.println("Even");
            } else {
                System.out.println("Odd");
            }
        }
    }

    Example 3: Algorithm to Find the Largest of Three Numbers

    Problem Statement

    Write an algorithm to find the largest among three numbers.

    Algorithm

    Steps

    • Start.
    • Take three numbers: A, B, and C.
    • Assume A is the largest and store it in max.
    • If B is greater than max, set max = B.
    • If C is greater than max, set max = C.
    • Display max as the largest number.
    • End.

    Pseudocode

    START
    INPUT A, B, C
    SET max = A
    
    IF B > max THEN
        SET max = B
    END IF
    
    IF C > max THEN
        SET max = C
    END IF
    
    DISPLAY max
    END

    Java Code

    public class Main {
        public static void main(String[] args) {
            int a = 10;
            int b = 25;
            int c = 15;
    
            int max = a;
    
            if (b > max) {
                max = b;
            }
    
            if (c > max) {
                max = c;
            }
    
            System.out.println("Largest Number: " + max);
        }
    }

    Output

    Largest Number: 25

    Types of Algorithms

    Algorithms can be classified based on the type of problem they solve and the method they use. Beginners do not need to master all types at once, but they should know the common categories.

    Algorithm Type Meaning Example
    Searching Algorithm Used to find an item from a collection. Linear Search, Binary Search
    Sorting Algorithm Used to arrange data in a specific order. Bubble Sort, Merge Sort, Quick Sort
    Recursive Algorithm Solves a problem by calling itself with smaller input. Factorial, Fibonacci
    Greedy Algorithm Makes the best choice at each step. Activity Selection, Dijkstra’s Algorithm
    Divide and Conquer Algorithm Breaks a problem into smaller parts and combines results. Merge Sort, Quick Sort
    Dynamic Programming Solves problems by storing results of repeated subproblems. Fibonacci, Knapsack Problem
    Graph Algorithm Works with nodes and connections. BFS, DFS, Shortest Path

    Three Basic Programming Concepts in Algorithms

    Many algorithms are built using three basic programming concepts: sequence, selection, and repetition.

    1

    Sequence

    Steps are executed one after another.

    Example: Take two numbers, add them, and display the result.

    2

    Selection

    A decision is made using a condition.

    Example: If marks are greater than or equal to 35, display Pass; otherwise, display Fail.

    3

    Repetition

    Steps are repeated using loops.

    Example: Print numbers from 1 to 10 using a loop.

    Example 4: Algorithm to Print Numbers from 1 to 5

    Algorithm

    Steps

    • Start.
    • Set counter = 1.
    • Repeat while counter is less than or equal to 5.
    • Display counter.
    • Increase counter by 1.
    • End loop.
    • End.

    Pseudocode

    START
    SET counter = 1
    
    WHILE counter <= 5 DO
        DISPLAY counter
        SET counter = counter + 1
    END WHILE
    
    END

    Java Code

    public class Main {
        public static void main(String[] args) {
            int counter = 1;
    
            while (counter <= 5) {
                System.out.println(counter);
                counter++;
            }
        }
    }

    Algorithm Efficiency

    Algorithm efficiency means how well an algorithm uses time and memory. A solution should not only be correct; it should also be efficient when working with large amounts of data.

    Efficiency Questions

    • How many steps does the algorithm take?
    • How much memory does the algorithm use?
    • Can the algorithm handle large input?
    • Is there a faster way to solve the same problem?
    • Can unnecessary repeated work be avoided?

    Time Complexity and Space Complexity

    Time complexity describes how the running time of an algorithm grows as input size increases. Space complexity describes how much memory an algorithm needs.

    Concept Meaning Simple Example
    Time Complexity Amount of time or number of steps needed. Searching every item in a list takes more time as list size grows.
    Space Complexity Amount of memory needed. Storing another copy of an array uses extra memory.
    Beginner Tip: First focus on writing a correct algorithm. After that, learn how to make it more efficient.

    Dry Run of an Algorithm

    A dry run means manually checking an algorithm step by step using sample input values. It helps students understand how variables change and whether the logic is correct.

    Dry Run Example

    Algorithm: Add two numbers.

    Step Value Explanation
    Input number1 10 First number is stored.
    Input number2 20 Second number is stored.
    Calculate sum 10 + 20 = 30 Addition is performed.
    Display output 30 The result is shown.

    Prerequisites Before Learning Algorithms

    Algorithms can be learned by beginners, but some basic programming knowledge makes learning easier.

    Basic Prerequisites

    • Basic understanding of what programming is.
    • Understanding of input, process, and output.
    • Knowledge of variables and data types.
    • Basic understanding of operators.
    • Understanding of conditions such as if and else.
    • Understanding of loops such as for and while.
    • Basic problem-solving mindset.
    • Patience to test and improve logic.

    Common Beginner Mistakes

    Mistakes

    • Starting code without writing an algorithm.
    • Writing unclear or incomplete steps.
    • Forgetting input or output requirements.
    • Using steps that never end.
    • Ignoring edge cases.
    • Confusing algorithm with programming syntax.
    • Not testing the algorithm manually.
    • Thinking only one solution exists for every problem.

    Better Habits

    • Understand the problem first.
    • Write clear input, process, and output.
    • Use simple and finite steps.
    • Write pseudocode before coding.
    • Test with sample values.
    • Think about boundary cases.
    • Improve the algorithm after it works.
    • Compare multiple approaches when possible.

    Practice Activity: Write an Algorithm

    This activity helps students practice writing algorithms before coding.

    Problem Statement

    Write an algorithm to calculate the area of a rectangle.

    IPO Analysis

    IPO Part Answer
    Input Length and width.
    Process area = length * width
    Output Area of rectangle.

    Algorithm

    Steps

    • Start.
    • Take the length of the rectangle.
    • Take the width of the rectangle.
    • Multiply length and width.
    • Store the result in area.
    • Display the area.
    • End.

    Pseudocode

    START
    INPUT length
    INPUT width
    SET area = length * width
    DISPLAY area
    END

    Java Solution

    public class Main {
        public static void main(String[] args) {
            int length = 10;
            int width = 5;
    
            int area = length * width;
    
            System.out.println("Area of Rectangle: " + area);
        }
    }

    Mini Quiz

    1

    What is an algorithm?

    An algorithm is a step-by-step procedure used to solve a problem or complete a task.

    2

    Is an algorithm dependent on a programming language?

    No. An algorithm is language-independent and can be implemented in different programming languages.

    3

    What does finite mean in an algorithm?

    Finite means the algorithm must stop after a limited number of steps.

    4

    What is pseudocode?

    Pseudocode is an English-like way of writing algorithm logic before writing actual code.

    5

    Why should we write an algorithm before coding?

    We should write an algorithm before coding because it makes the logic clear and reduces programming mistakes.

    Interview Questions on Algorithm

    1

    Define algorithm.

    An algorithm is a finite sequence of well-defined steps used to solve a specific problem.

    2

    What are the main characteristics of an algorithm?

    The main characteristics are clarity, finiteness, input, output, effectiveness, and correctness.

    3

    What is the difference between an algorithm and a program?

    An algorithm is the logical plan for solving a problem, while a program is the implementation of that plan in a programming language.

    4

    What is the purpose of a dry run?

    A dry run is used to manually test an algorithm step by step using sample input values.

    5

    Why is algorithm efficiency important?

    Algorithm efficiency is important because a program should solve problems correctly while using time and memory properly.

    Quick Summary

    Concept Meaning
    Algorithm Step-by-step method to solve a problem.
    Input Data accepted by the algorithm.
    Output Result produced by the algorithm.
    Finiteness Algorithm must stop after limited steps.
    Pseudocode English-like representation of algorithm logic.
    Flowchart Visual representation of an algorithm.
    Dry Run Manual checking of algorithm steps.
    Efficiency How well an algorithm uses time and memory.

    Final Takeaway

    An algorithm is the foundation of programming problem solving. It helps students think logically, organize steps clearly, and write better code. Before writing any program, always understand the problem, identify input and output, write the algorithm, test it with sample values, and then convert it into code.