Why variables are needed in C - Performance Analysis
We want to see how using variables affects the steps a program takes.
How does the program's work change when it stores and uses values?
Analyze the time complexity of the following code snippet.
#include <stdio.h>
int main() {
int a = 5;
int b = 10;
int sum = a + b;
printf("Sum is %d\n", sum);
return 0;
}
This code stores two numbers in variables, adds them, and prints the result.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Simple addition and printing.
- How many times: Each operation runs once.
Since there are no loops or repeated steps, the work stays the same no matter what.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 5 |
| 100 | 5 |
| 1000 | 5 |
Pattern observation: The number of steps does not grow with input size.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how big the input is.
[X] Wrong: "Using variables makes the program slower because it adds extra steps."
[OK] Correct: Variables just hold values and do not cause repeated work; they help organize data without slowing down the program.
Understanding how variables affect program steps shows you know how programs manage data efficiently, a key skill in coding.
"What if we added a loop that uses variables multiple times? How would the time complexity change?"