Complete the code to print all elements of the array using a for loop.
#include <iostream> int main() { int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < n; i++) { std::cout << arr[[1]] << " "; } return 0; }
The variable i is used as the index to access each element of the array during traversal.
Complete the code to calculate the sum of all elements in the array.
#include <iostream> int main() { int arr[] = {10, 20, 30, 40}; int n = sizeof(arr) / sizeof(arr[0]); int sum = 0; for (int i = 0; i < n; i++) { sum += arr[[1]]; } std::cout << sum << std::endl; return 0; }
The loop variable i is used to access each element to add it to sum.
Fix the error in the loop condition to correctly traverse the array.
#include <iostream> int main() { int arr[] = {5, 10, 15}; int n = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i [1] n; i++) { std::cout << arr[i] << " "; } return 0; }
The loop should run while i is less than n to avoid going out of array bounds.
Fill both blanks to create a loop that prints elements at even indices only.
#include <iostream> int main() { int arr[] = {2, 4, 6, 8, 10, 12}; int n = sizeof(arr) / sizeof(arr[0]); for (int i = [1]; i < n; i [2]) { std::cout << arr[i] << " "; } return 0; }
Start at index 0 and increase i by 2 each time to access even indices.
Fill all three blanks to create a loop that prints elements in reverse order.
#include <iostream> int main() { int arr[] = {3, 6, 9, 12, 15}; int n = sizeof(arr) / sizeof(arr[0]); for (int i = [1]; i [2] 0; i [3]) { std::cout << arr[i] << " "; } return 0; }
Start from the last index n - 1, loop while i is greater than 0, and decrement i each time.