Fix my C++ program. It's supposed to initialize and print an array of n elements, find…
- User
Fix my C++ program. It's supposed to initialize and print an array of n elements, find the index of the 1st even element (val). Then transform the last (val) elements by multiplying it by the value of the first odd element. My code doesn't work correctly as it multiplies the wrong quantity of last elements at the very end. #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) { for (int i = 0; i < n; ++i) { if (a[i] % 2 == 0) { return i; } } cout << "No even elements found"; return -1; }
int firstOddElem(int* a, int n, int ind) { for (int i = 0; i < n; ++i) { if (a[i] % 2 != 0) { return a[i]; } } return -1; }
int main() { srand(time(0)); 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 << "\nArr before:" << endl; print(arr, n); int ind = firstEvenIndex(arr, n); if (ind != -1) { int elem = firstOddElem(arr, n, ind); cout << "\nIndex of the first even element: " << ind << endl; cout << "First odd element: " << elem << endl; for (int i = ind + 1; i < n; ++i) arr[i] *= elem; cout << "\nArr after:" << endl; print(arr, n); } delete[] arr; arr = nullptr; return 0;}
- Assistant
Here's the fixed version of your C++ program:
#include <iostream> #include <cstdlib> #include <ctime> 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) { for (int i = 0; i < n; ++i) { if (a[i] % 2 == 0) { return i; } } cout << "No even elements found"; return -1; } int firstOddElem(int* a, int n, int ind) { for (int i = ind; i < n; ++i) { if (a[i] % 2 != 0) { return a[i]; } } return -1; } int main() { srand(time(0)); 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 << "\nArr before:" << endl; print(arr, n); int ind = firstEvenIndex(arr, n); if (ind != -1) { int elem = firstOddElem(arr, n, ind); if (elem != -1) { cout << "\nIndex of the first even element: " << ind << endl; cout << "First odd element: " << elem << endl; for (int i = ind + 1; i < n; ++i) arr[i] *= elem; } } cout << "\nArr after:" << endl; print(arr, n); delete[] arr; arr = nullptr; return 0; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.