Assignment 1 (1)
Assignment 1 (1)
Instructions:
Analyze the following C++ code snippets. For each code snippet, calculate its time complexity. Explain your
reasoning and, if needed, describe how the time complexity is derived. Write down the time complexity
in Big O notation (e.g., O(1), O(n), O(log n), O(n^2)).
Code Snippet 1
C++ Code Time Complexity Analysis
int main() {
int a = 10;
int b = 20;
int result = a + b; // Single operation
cout << "Result: " << result << endl;
return 0;
O(1)
}
Code Snippet 2
C++ Code Time Complexity Analysis
int main() {
int n = 100;
int sum = 0;
for (int i = 1; i <= n; i++) { // Loop from 1 to n
}
sum += i;
}
}
cout << i * j << endl;
O(n^2))
return 0;
}
Code Snippet 4
C++ Code Time Complexity Analysis
int binarySearch(int arr[], int n, int target) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
found
if (arr[mid] == target) return mid; // Element
Code Snippet 5
C++ Code Time Complexity Analysis
int main() {
int n = 10;
for (int i = 1; i <= n; i *= 2) { // Logarithmic loop
for (int j = 1; j <= n; j++) { // Linear loop inside
}
cout << i + j << endl; O(n)
}
return 0;}