I'm doing a program that finds the max value in a array. I done it but I found a strange bug.
#include<iostream>
using namespace std;
int main() {
int n; //input number of elements in
cin >> n;
int arr[n];
for (int i = 0; i < n; i ) {
cin >> arr[i]; //input array's elements
} int max_value = arr[0];
for (int i = 1; i <= n; i ) {
if (arr[i] > max_value) {
max_value = arr[i];
}
} cout << max_value;
return 0;
}
When I put 5 as first line for the number of elements and 2, 7, 6, 8, 9 as the elements of the array. It returns 16 instead of 9. Please help
CodePudding user response:
In Arrays the first index starts with 0
and ends in n - 1
assuming the array is of length n
so when looping from i = 1
to i <= n
. n is now larger than n - 1
.
the solution would be to start from 0
and end at i < n
hence.
#include<iostream>
using namespace std;
int main() {
int n; //input number of elements in
cin >> n;
int arr[n];
for (int i = 0; i < n; i ) {
cin >> arr[i]; //input array's elements
} int max_value = arr[0];
for (int i = 0; i < n; i ) {
if (arr[i] > max_value) {
max_value = arr[i];
}
}
cout << max_value;
return 0;
}
you could also use the std::max
function like so:
for(int i = 0; i < n; i ) {
max_value = max(max_value, arr[i]);
}
CodePudding user response:
in your second for do this
for (int i = 1; i < n; i ) {
if (arr[i] > max_value) {
max_value = arr[i];
}
delete '=' from i <= n because i is index which start from 0
and instead of this
int arr[n];
do this
int arr* = new int[n];