Course contentsShow
← C
Lesson 304 of 1,2194. Control FlowFree lesson

Performance: O(n^2) complexity introduction

Performance: O(n^2) complexity introduction

What you'll learn: How nested loops can cause your program's execution time to grow exponentially as your data increases.

The Cost of Nests

When you put one loop inside another, you aren't just adding work; you are multiplying it. In computer science, we often describe the efficiency of an algorithm using "Big O" notation. A single loop that runs nn times is O(n)O(n), or linear. But when you nest a loop of nn iterations inside another loop of nn iterations, you create O(n2)O(n^2) complexity, also known as quadratic time.

Think of it like cleaning a square floor made of tiles. If the floor is 5 tiles wide and 5 tiles long (n=5n=5), you have to scrub 25 tiles. If you double the width and length to 10 (n=10n=10), you don't just do double the work—you now have 100 tiles to scrub. The work grew four times larger because 10210^2 is 100.

Seeing the Multiplier in Code

In C, this usually happens when you compare every item in a list to every other item. Notice how the total number of "steps" performed by the computer explodes as n grows.

#include <stdio.h>

int main() {
    int n = 10;
    int counter = 0;

    // The outer loop runs 'n' times
    for (int i = 0; i < n; i++) {
        // For EVERY single 'i', this inner loop also runs 'n' times
        for (int j = 0; j < n; j++) {
            counter++; 
        }
    }

    printf("For n = %d, the inner loop ran %d times.\n", n, counter);
    return 0;
}

If you change n to 100, the counter will hit 10,000. If you change it to 100,000, the counter hits 10 billion. On a standard processor, a 10-billion-step operation might take several seconds, whereas a single loop of 100,000 steps would finish in the blink of an eye.

Why It Matters

As a C programmer, you have to be careful with nested loops when dealing with large datasets. While O(n2)O(n^2) is perfectly fine for small arrays (like a 3x3 game grid), it can make your program feel "frozen" or slow if you try to process millions of records using this structure. Always ask yourself: "If my input size doubles, will my program take four times as long to finish?"

Key takeaway

Nested loops result in O(n2)O(n^2) complexity, meaning the total work performed is the square of the input size.