0% found this document useful (0 votes)
66 views

CS502 Assignment 1 Solution

Cs502 Assignment

Uploaded by

sohail.m03154
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

CS502 Assignment 1 Solution

Cs502 Assignment

Uploaded by

sohail.m03154
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

Bc200401272

Question No. 1

Consider the following piece of code of a function that processes a list of integers in the followin
g way:

int n = arr.size(); // Step 1

// First loop: print each element of the array


for (int i = 0; i < n; ++i) { // Step 2
std::cout << arr[i] << std::endl; // Step 3
}

// Second nested loops: print the product of each triplet of elements


for (int j = 0; j < n; ++j) { // Step 4
for (int k = 0; k < n; ++k) { // Step 5
for (int l = 0; l < n; ++l) { // Step 6
std::cout << arr[j] * arr[k] * arr[l] << std::endl; // Step 7
}
}
}

You have to determine the time complexity of the given C++ code by analysing each line of the
code and also determine the overall time complexity of this code. You are required to show all st
eps in detail.

Answer:
int n = arr.size(); // Step 1
Answer:

Time Complexity: This step involves fetching the size of the array, which is an O(1)
operation. Therefore, the time complexity for Step 1 is O(1).

// First loop: print each element of the array


for (int i = 0; i < n; ++i) { // Step 2
std::cout << arr[i] << std::endl; // Step 3
}

Answer:

 Loop Iterations: This is a single loop that runs from i = 0 to i = n - 1. So, it


will run n times.
 Time Complexity: The operation inside the loop (printing the element) is
O(1). Therefore, the time complexity of this part is O(n), where n is the size
of the array.

// Second nested loops: print the product of each triplet of elements


for (int j = 0; j < n; ++j) { // Step 4
for (int k = 0; k < n; ++k) { // Step 5
for (int l = 0; l < n; ++l) { // Step 6
std::cout << arr[j] * arr[k] * arr[l] << std::endl; // Step 7
}
}
}
Answer:
 Loop Iterations:
o The outermost loop (Step 4) runs n times (from j = 0 to j = n-1).
o The middle loop (Step 5) also runs n times (from k = 0 to k = n-1).
o The innermost loop (Step 6) also runs n times (from l = 0 to l = n-1).

This is a set of three nested loops, each iterating n times.


Time Complexity: O(n³)
Overall Time Complexity Analysis

1. The initialization (Step 1) takes constant time: O(1)


2. The first loop (Steps 2-3) takes linear time: O(n)
3. The nested loops (Steps 4-7) take cubic time: O(n³)

To determine the overall time complexity, we need to sum these up:

O(1) + O(n) + O(n³)

When we have different terms in the time complexity, we consider the term wit
h the highest order of growth. In this case, O(n³) dominates the others for large
values of n.

Therefore, the overall time complexity of this code is O(n³).

You might also like