Launch your tech mastery with us—your coding journey starts now!
Course Content
Data Structure
 

What is an Algorithm?

The Simple Definition

An algorithm is simply a step-by-step set of instructions to solve a problem or complete a task.

Think of it like a recipe for cooking! Just like a recipe tells you exactly what to do to make a dish, an algorithm tells the computer exactly what to do to solve a problem.

Real-Life Examples of Algorithms

You use algorithms every day without even realizing it!

Example 1: Making Tea ☕

Steps:

  1. Boil water
  2. Put tea bag in cup
  3. Pour hot water into cup
  4. Wait 2 minutes
  5. Remove tea bag
  6. Add sugar (optional)
  7. Stir and enjoy!

This is an algorithm! It’s a clear set of steps that anyone can follow.

Example 2: Finding Your Phone 📱

Steps:

  1. Check your pocket
  2. If found, stop searching
  3. If not, check the table
  4. If found, stop searching
  5. If not, check the bedroom
  6. Keep checking until you find it

Example 3: Brushing Your Teeth 🪥

Steps:

  1. Pick up toothbrush
  2. Apply toothpaste
  3. Wet the brush
  4. Brush for 2 minutes
  5. Rinse mouth
  6. Rinse toothbrush

See? You’ve been following algorithms your whole life!

Why Do We Need Algorithms in Programming?

Computers are very powerful but also very dumb. They need exact instructions for everything.

You can’t tell a computer: “Hey, add these numbers.”

You must tell it:

  1. Take the first number
  2. Take the second number
  3. Add them together
  4. Show the result

That’s an algorithm!

Characteristics of a Good Algorithm

A good algorithm must have these qualities:

1. Clear and Unambiguous

Every step should be crystal clear with no confusion.

❌ Bad: “Add some sugar”
✅ Good: “Add 2 teaspoons of sugar”

2. Has Input

The algorithm takes some input (data to work with).

Example: Two numbers to add → Input: 5 and 10

3. Has Output

The algorithm produces a result.

Example: Sum of numbers → Output: 15

4. Finite Steps

The algorithm must end after a certain number of steps (not run forever!).

❌ Bad: Keep counting numbers forever
✅ Good: Count from 1 to 10, then stop

5. Works Correctly

The algorithm should give the right answer every time.

How to Write an Algorithm

There are three main ways to write algorithms:

Method 1: Plain English (Natural Language)

Write steps in simple sentences.

Example: Algorithm to find the largest of three numbers

Step 1: Start
Step 2: Read three numbers: A, B, and C
Step 3: Assume A is the largest
Step 4: If B is greater than A, then B is the largest
Step 5: If C is greater than the current largest, then C is the largest
Step 6: Print the largest number
Step 7: Stop

Method 2: Pseudocode

Pseudocode is like a mix of English and programming. It’s more structured than plain English but easier than actual code.

Example: Algorithm to check if a number is even or odd

BEGIN
    INPUT number
    
    IF number % 2 == 0 THEN
        PRINT "Even"
    ELSE
        PRINT "Odd"
    END IF
    
END

Example: Algorithm to print numbers from 1 to 5

BEGIN
    FOR i = 1 to 5 DO
        PRINT i
    END FOR
END

Method 3: Flowchart

A flowchart uses shapes and arrows to show the flow of steps visually.

Common Flowchart Symbols:

  • Oval = Start/End
  • Rectangle = Process/Action
  • Diamond = Decision (Yes/No questions)
  • Arrow = Flow direction
  • Parallelogram = Input/Output

Example: Flowchart to check if a number is positive

A simple flowchart showing the process to check if a number is positive. It starts with “Start,” then “Input Number,” followed by a decision diamond asking “Is number > 0?”. If Yes, it prints “Positive” and ends. If No, it prints “Not Positive” and ends.

Star Pattern Printing Examples

Pattern 1: Right Triangle (Most Basic)

This is the foundation of all patterns. If you understand this, you can solve any pattern!

Output:

*
**
***
****
*****

Algorithm:

Step 1: Start
Step 2: For row from 1 to 5:
        Step 2.1: For col from 1 to row:
                  Print star
        Step 2.2: Move to next line
Step 3: Stop

Logic Explanation:

  • Row 1: Print 1 star
  • Row 2: Print 2 stars
  • Row 3: Print 3 stars
  • Row 4: Print 4 stars
  • Row 5: Print 5 stars

Key Point: Number of stars = Row number

Java Code:

java
public class RightTriangle {
    public static void main(String[] args) {
        int n = 5;
        
        // Outer loop for rows
        for (int row = 1; row <= n; row++) {
            // Inner loop for columns (stars)
            for (int col = 1; col <= row; col++) {
                System.out.print("*");
            }
            System.out.println(); // Move to next line
        }
    }
}

Why It’s Important:

  • Teaches you nested loops
  • Foundation for all other patterns
  • Most frequently asked in interviews
 

Pattern 2: Pyramid (Most Popular)

This is the most asked pattern in coding interviews!

Output:

    *
   ***
  *****
 *******
*********

Algorithm:

Step 1: Start
Step 2: For row from 1 to 5:
        Step 2.1: Print (n - row) spaces
        Step 2.2: Print (2 × row - 1) stars
        Step 2.3: Move to next line
Step 3: Stop

Logic Explanation:

Row Spaces Stars Formula
1 4 1 spaces = 5-1=4, stars = 2×1-1=1
2 3 3 spaces = 5-2=3, stars = 2×2-1=3
3 2 5 spaces = 5-3=2, stars = 2×3-1=5
4 1 7 spaces = 5-4=1, stars = 2×4-1=7
5 0 9 spaces = 5-5=0, stars = 2×5-1=9

Key Formulas:

  • Spaces = n – row
  • Stars = 2 × row – 1

Java Code:

java
public class Pyramid {
    public static void main(String[] args) {
        int n = 5;
        
        for (int row = 1; row <= n; row++) {
            
            // Print spaces
            for (int space = 1; space <= n - row; space++) {
                System.out.print(" ");
            }
            
            // Print stars
            for (int star = 1; star <= 2 * row - 1; star++) {
                System.out.print("*");
            }
            
            System.out.println(); // Move to next line
        }
    }
}

Why It’s Important:

  • Most frequently asked in interviews (Google, Amazon, Microsoft)
  • Tests your mathematical thinking
  • Combination of spaces and stars
 

Pattern 3: Diamond (Most Challenging)

This combines pyramid + inverted pyramid. Master this and you’re ready for any pattern!

Output:

    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Algorithm:

Step 1: Start
Step 2: Print upper half (pyramid with 5 rows)
Step 3: Print lower half (inverted pyramid with 4 rows)
Step 4: Stop

Logic Explanation:

Upper Half (Rows 1-5):

  • Same as Pyramid pattern

Lower Half (Rows 6-9):

  • Row 6: 1 space, 7 stars (like row 4 of pyramid)
  • Row 7: 2 spaces, 5 stars (like row 3 of pyramid)
  • Row 8: 3 spaces, 3 stars (like row 2 of pyramid)
  • Row 9: 4 spaces, 1 star (like row 1 of pyramid)

Java Code:

java
public class Diamond {
    public static void main(String[] args) {
        int n = 5;
        
        // Upper half - Pyramid
        for (int row = 1; row <= n; row++) {
            // Print spaces
            for (int space = 1; space <= n - row; space++) {
                System.out.print(" ");
            }
            // Print stars
            for (int star = 1; star <= 2 * row - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
        
        // Lower half - Inverted Pyramid
        for (int row = n - 1; row >= 1; row--) {
            // Print spaces
            for (int space = 1; space <= n - row; space++) {
                System.out.print(" ");
            }
            // Print stars
            for (int star = 1; star <= 2 * row - 1; star++) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

Why It’s Important:

  • Combines multiple concepts
  • Tests problem decomposition skills
  • Shows you can handle complex patterns
 

Tips for Writing Good Algorithms

  1. Understand the problem first – Know what you’re trying to solve
  2. Break it into small steps – Don’t try to solve everything at once
  3. Use simple language – Anyone should be able to understand
  4. Test with examples – Try your algorithm with sample inputs
  5. Think about edge cases – What if the input is 0? Negative? Very large?

Practice Exercises for You! 💪

Try writing algorithms and Java code for these problems:

  1. Print all even numbers from 1 to 20
  2. Find the sum of digits of a number (123 → 1+2+3 = 6)
  3. Count the number of digits in a number
  4. Print the multiplication table of a number
  5. Find if a year is a leap year
  6. Convert Celsius to Fahrenheit
  7. Find GCD (Greatest Common Divisor) of two numbers
  8. Check if a number is Armstrong number (153 = 1³ + 5³ + 3³)