Runtime Comparison of Loop Structures
Calculate statement execution counts and informal run-time comparison of iterative statements.
Consider these two code segments that accomplish the same task:
// Segment A
int sum = 0;
for (int i = 0; i < n; i++) {
sum += arr[i];
}
// Segment B
int sum = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < 1; j++) {
sum += arr[i];
}
}
Which statement best compares the run-time efficiency of these segments?
A
Segment B is less efficient because it has quadratic time complexity
B
Segment A is more efficient because it has fewer loop headers to execute
C
Segment B is more efficient because nested loops are always faster
D
Both segments have the same run-time efficiency since they perform the same number of operations
Question Leaderboard
| Rank | |||||
|---|---|---|---|---|---|
| #1 | hitrishabhatia | 1 | 1 | 0m 00s | 100 |
| #2 | suhanakochhar006 | 0 | 2 | 0m 00s | -20 |
| #3 | ravi.palepu | 0 | 1 | 0m 58s | -68 |
| #4 | y.seong2027 | 0 | 1 | 1m 10s | -80 |
Items per page:
10
1 – 4 of 4
APFIVE