Why functions are needed in C++ - Performance Analysis
We want to see how using functions affects the time it takes for a program to run.
Does breaking code into functions change how the program grows with bigger inputs?
Analyze the time complexity of the following code snippet.
#include <iostream>
void printNumbers(int n) {
for (int i = 0; i < n; i++) {
std::cout << i << std::endl;
}
}
int main() {
printNumbers(5);
return 0;
}
This code prints numbers from 0 up to n-1 using a function.
Look for loops or repeated steps.
- Primary operation: The for-loop inside the function that prints numbers.
- How many times: It runs n times, once for each number.
As n gets bigger, the loop runs more times, so the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times printing |
| 100 | 100 times printing |
| 1000 | 1000 times printing |
Pattern observation: The work grows directly with n; double n means double work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the input size.
[X] Wrong: "Using a function makes the program slower or more complex."
[OK] Correct: Functions just organize code; they don't add extra loops or slow down the main work.
Understanding how functions affect time helps you write clear code without worrying about hidden slowdowns.
"What if the function called itself recursively instead of using a loop? How would the time complexity change?"