0
0
Cprogramming~5 mins

Goto statement overview in C - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Goto statement overview
O(n)
Understanding Time Complexity

Let's see how using the goto statement affects how long a program takes to run.

We want to know if jumping around with goto changes the work done as input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


#include <stdio.h>

int main() {
    int i = 0;
start:
    if (i >= 5) goto end;
    printf("%d\n", i);
    i++;
    goto start;
end:
    return 0;
}
    

This code prints numbers from 0 to 4 using goto to loop instead of a normal loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The repeated printing and incrementing controlled by goto.
  • How many times: The code jumps back and repeats 5 times before stopping.
How Execution Grows With Input

Each time the input limit increases, the number of jumps and prints grows the same way.

Input Size (n)Approx. Operations
55 jumps and prints
1010 jumps and prints
100100 jumps and prints

Pattern observation: The work grows directly with the input size, one step per input.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in a straight line as the input number grows.

Common Mistake

[X] Wrong: "Using goto makes the program faster or slower in a big way."

[OK] Correct: Goto just changes how the code jumps but does not change how many times the main work happens.

Interview Connect

Understanding how goto affects time helps you see that structure changes don't always change work done.

Self-Check

"What if we replaced the goto with a for loop? How would the time complexity change?"