Introduction to Algorithms
Learn what algorithms are and how to write step-by-step solutions to problems. Understand the building blocks of all computer programs.
Track Your Progress
Sign in to save your learning progress
What You Will Learn
- ✓Define what an algorithm is
- ✓Write algorithms in plain English
- ✓Understand algorithm characteristics (finite, clear, effective)
- ✓Convert real-world problems into step-by-step solutions
What is an Algorithm?
An algorithm is a step-by-step procedure to solve a problem or accomplish a task. It's like a recipe that tells you exactly what to do, in what order!
Before writing any code, programmers first think about the steps needed to solve a problem. These steps, when written down clearly, form an algorithm. An algorithm is the blueprint of your program.
01Algorithms in Daily Life
You use algorithms every day without realizing it! Here are some examples:
Making an Omelette
- 1. Take 2 eggs
- 2. Break eggs into a bowl
- 3. Add salt and pepper
- 4. Beat the mixture
- 5. Heat oil in pan
- 6. Pour mixture into pan
- 7. Cook until done
- 8. Serve on plate
Driving to School
- 1. Get in the car
- 2. Put on seatbelt
- 3. Start the engine
- 4. Drive to first intersection
- 5. Turn left
- 6. Continue straight for 2 km
- 7. Turn right at school
- 8. Park the car
Key Insight
An algorithm is simply a clear, ordered set of instructions that leads to a specific result. The same applies to computer programs!
02Characteristics of a Good Algorithm
Not every set of instructions is a good algorithm. A proper algorithm should have these characteristics:
Clear & Unambiguous
Each step must be precise and clear. No confusion about what to do.
Well-Defined Inputs
May have zero or more inputs that are clearly specified.
Well-Defined Outputs
Must produce at least one output or result.
Finite Steps
Must end after a finite number of steps. Cannot run forever!
Effective
Each step should be simple and doable.
Language Independent
Can be implemented in any programming language.
03Example: Algorithm to Add Two Numbers
Let's write an algorithm to add two numbers. First, we'll write it in plain English, then in code.
Algorithm Steps:
C Code:
1#include <stdio.h>23int main() {4 int num1, num2, sum;5 6 printf("Enter first number: ");7 scanf("%d", &num1);8 9 printf("Enter second number: ");10 scanf("%d", &num2);11 12 sum = num1 + num2;13 14 printf("Sum = %d", sum);15 return 0;16}04Example: Find Largest of Three Numbers
This algorithm uses conditions to make decisions. Let's find the largest among three numbers.
Algorithm:
Test Your Algorithm!
Try with A=5, B=9, C=3. Following the algorithm: Is 5 > 9? No. Is 9 > 5 AND 9 > 3? Yes! So largest = 9. ✓
04bWays to Represent Algorithms
There are several ways to write down and communicate algorithms. Each method has its advantages depending on the situation and audience.
Natural Language
Written in plain English (or your native language). Easy to understand but can be ambiguous. Best for initial brainstorming and explaining to non-programmers.
Example: "Take the first number, add it to the second number, display the result."
Flowcharts
Visual diagrams using shapes and arrows. Great for showing flow and decisions. Universally understood. Perfect for complex branching logic.
See our Flowcharts tutorial for details!
Pseudocode
A mix of natural language and programming structure. More precise than English, easier than real code. The most common format in textbooks and interviews.
PRINT "Pass"
ELSE
PRINT "Fail"
# Structured English
Uses keywords like IF, THEN, ELSE, WHILE, FOR in English sentences. More formal than natural language, less technical than pseudocode.
Common in business analysis and requirements documents.
Which Format Should I Use?
For learning: start with natural language, then add pseudocode structure. For interviews: pseudocode is expected. For team communication: flowcharts work great. For documentation: use all three together for clarity.
04cWhy Algorithm Efficiency Matters
Not all algorithms that solve a problem are equally good. Some are faster, some use less memory. As you progress, you'll learn to analyze and choose efficient algorithms.
Example: Finding a Number in a List
Slow: Check Every Element
Look at each item one by one until you find it. For 1 million items, might need 1 million checks!
Time: O(n) — linear
Fast: Binary Search (sorted list)
Check the middle, eliminate half each time. For 1 million items, only ~20 checks needed!
Time: O(log n) — logarithmic
Don't worry about the O notation now — just know that algorithm choice can mean the difference between seconds and hours of runtime!
05Algorithm vs Program
What's the difference between an algorithm and a program? Let's compare:
| Algorithm | Program |
|---|---|
| Written in plain English or pseudocode | Written in programming language (C, Python, etc.) |
| Language independent - can be converted to any language | Language specific - follows syntax rules |
| Blueprint / Design phase | Implementation / Building phase |
| Easy to understand by anyone | Requires programming knowledge |
| Cannot be executed directly | Can be compiled and run |
Pro Tip: Always Algorithm First!
Before writing any code, always write your algorithm first. It helps you:
• Think clearly about the problem
• Avoid bugs and logical errors
• Make coding much easier
06Practice: Write Your Own Algorithm
Try writing algorithms for these problems. Remember: use plain English, be specific, and number your steps!
# Problem 1: Check Even or Odd
Write an algorithm to check if a number is even or odd.
Hint: Use modulus (%) - if number % 2 == 0, it's even
Problem 2: Calculate Area of Rectangle
Write an algorithm to find area given length and width.
Hint: Area = length × width
07Frequently Asked Questions
Q:What's the difference between an algorithm and a program?
A: An algorithm is the idea — the step-by-step logic in plain language. A program is the implementation — the algorithm written in a specific programming language. One algorithm can be implemented in many languages (C, Python, Java).
Q:Why should I write algorithms before coding?
A: It's easier to think about logic without worrying about syntax. You catch errors in planning, not debugging. It clarifies your thinking and makes coding faster. Many professional developers sketch algorithms before writing any code.
Q:How detailed should my algorithm be?
A: Detailed enough that someone else could follow it without guessing. Each step should be simple and unambiguous. If a step is complex, break it into sub-steps. The test: could a non-programmer follow it?
Q:Are there "best" algorithms?
A: Different algorithms have different trade-offs: speed, memory usage, simplicity. For sorting, QuickSort is generally fast but MergeSort is more predictable. "Best" depends on your specific needs. Algorithm analysis helps you choose.
Q:What is Big O notation and why should I care?
A: Big O describes how an algorithm's runtime grows with input size. O(n) means linear growth; O(n²) means quadratic. Knowing this helps you predict performance and choose the right algorithm. For 1000 items, O(n) is 1000 operations; O(n²) is 1,000,000!
Q:How do I test if my algorithm is correct?
A: Trace through your algorithm with simple examples by hand first. Test edge cases: empty input, one element, duplicates, negative numbers, already-sorted data. Compare output against known correct results. Write multiple test cases before writing code.
!Code Pitfalls: Common Mistakes & What to Watch For
Common Mistakes with Algorithms
Copied code can produce code but often misses crucial algorithmic thinking:
- ✗Wrong complexity: Beginners often pick O(n²) algorithms when O(n log n) exists, causing performance disasters on large data
- ✗Infinite loops: Beginners often forget termination conditions or creates loops that never end
- ✗Off-by-one errors: Beginners often miscount loop iterations, causing algorithms to miss first or last elements
- ✗Missing base cases: Recursive algorithms from Copied code often lack proper termination
Design Algorithms Yourself
Write the algorithm in plain English first. Verify it handles all cases. Then Copied code can help implement it — but you've already done the hard thinking. Understanding algorithms lets you spot mistakes immediately.
08Summary
What You Learned:
- ✓Algorithm = step-by-step procedure to solve a problem
- ✓Must be clear, finite, and effective
- ✓Should have defined inputs and outputs
- ✓Algorithm is the blueprint, program is the implementation
- ✓Always write algorithm first, then code
Test Your Knowledge
Related Tutorials
What is Programming?
Understand what programming really is before writing any code. Learn why we program, types of programming languages, and key concepts every beginner should know.
Understanding Flowcharts
Learn to draw flowcharts - visual diagrams that represent algorithms. Master the standard symbols for start, process, decision, and input/output.
Why Learn C? History of C
Discover why C is still one of the most important programming languages after 50+ years. Learn its history, where it's used today, and why learning C gives you an edge in your programming career.
Have Feedback?
Found something missing or have ideas to improve this tutorial? Let us know on GitHub!