Write a C++ program. Initialize and print an array of n elements. Find the index of the…
- User
Write a C++ program. Initialize and print an array of n elements. Find the index of the 1st even element (remember the returned number). Then transform the last (returned number) elements by multiplying it by the value of the first odd element.
- Assistant
Here is the C++ code fulfilling the given requirements:
#include <iostream> int main() { int n; std::cout << "Enter the number of elements: "; std::cin >> n; int arr[n]; std::cout << "Enter the elements of the array: "; for (int i = 0; i < n; i++) { std::cin >> arr[i]; } int evenIndex = -1; for (int i = 0; i < n; i++) { if (arr[i] % 2 == 0) { evenIndex = i; break; // found the first even element, no need to continue the loop } } if (evenIndex != -1) { int firstOddElement; for (int i = 0; i < n; i++) { if (arr[i] % 2 != 0) { firstOddElement = arr[i]; break; } } for (int i = evenIndex + 1; i < n; i++) { arr[i] *= firstOddElement; } std::cout << "Updated array after multiplying: "; for (int i = 0; i < n; i++) { std::cout << arr[i] << " "; } std::cout << std::endl; } else { std::cout << "No even element found in the array." << std::endl; } return 0; } - User
Fix my code. It's supposed to do the same task. #include
using std::cout; using std::cin; using std::endl;
void print(int* a, int n) { for (int i = 0; i < n; ++i) cout << a[i] << " "; cout << "\n"; }
int firstEvenIndex(int* a, int n) { int index = -1; for (int i = 0; i < n; ++i) { if (a[i] % 2 == 0) { index = i; break; return index; } else { cout << "No even elements found"; return 0; }
}}
int firstOddElem(int* a, int n, int ind) { int element; for (int i = 0; i < n; ++i) { if (a[i] % 2 != 0) { element = a[i]; } break; return element; } }
int main() { int n; cout << "Enter array's length: "; cin >> n; if (n < 0) n = -n; else if (n == 0) n = 1;
int* arr = new int[n]; if (arr == nullptr) { cout << "\nMemory error"; return 1; } for (int i = 0; i < n; ++i) arr[i] = rand() % 21 - 10;/* cout << "Enter " << n << " elements:" << endl; for (int i = 0; i < n; ++i) { cout << "a[" << i << "] = "; cin >> arr[i]; } */
- Assistant