0
0
MATLABdata~5 mins

Why control flow directs program logic in MATLAB - Performance Analysis

Choose your learning style9 modes available
Time Complexity: Why control flow directs program logic
O(n)
Understanding Time Complexity

Control flow decides which parts of a program run and how often. Understanding its time cost helps us see how program speed changes with input size.

We want to know how the program's running time grows when control flow changes the path of execution.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


for i = 1:n
    if mod(i,2) == 0
        disp(i)
    else
        disp(i^2)
    end
end
    

This code loops from 1 to n and uses an if-else to decide what to display for each number.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for-loop runs from 1 to n.
  • How many times: Exactly n times, once per number.
How Execution Grows With Input

Each number from 1 to n is checked and displayed once, so work grows directly with n.

Input Size (n)Approx. Operations
1010 checks and displays
100100 checks and displays
10001000 checks and displays

Pattern observation: The number of operations grows steadily as n grows; doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the program takes longer in direct proportion to the input size.

Common Mistake

[X] Wrong: "The if-else inside the loop doubles the time because it has two paths."

[OK] Correct: The if-else only chooses one path each time, so it does not multiply the work; it still runs once per loop.

Interview Connect

Understanding how control flow affects time helps you explain program speed clearly and shows you can think about efficiency in real code.

Self-Check

"What if the loop contained another nested loop inside the if-branch? How would the time complexity change?"