✏️ Explanatory Question

Calculate the run-time efficiency of the following single loop:

for (i = 1; i <= n; i++) {
    print(i);
}

👁 0 Views
📘 Detailed Answer
🟢 Easy
💡

Answer with Explanation

Ans. The variable i iterates n times. Therefore, the run-time efficiency is O(n).

💡 Explanation:

The loop begins with i = 1 and increases i by 1 after every iteration. It continues until i becomes greater than n.

Therefore, the loop body executes exactly n times. The print(i) statement performs a constant amount of work during each iteration.

Total work = n × O(1) = O(n).

Hence, a single loop that processes all n items has linear time complexity, O(n).

Memory tip: One loop running from 1 to n generally means O(n).