Firstly, see Why should I not #include <bits/stdc++.h>?.
Secondly, arrays MUST have a constant value. They cannot get their value from any sort of input, etc.
Thirdly, you have an infinite loop:
for (i = 1; i+1<n;i=i++){
if(arr[i]>arr[i-1]&&arr[i]>arr[i+1])
t = arr[i];
max.push_back(t);
}
When we enter the for
loop, we begin with i
at 1 and (for the example, n
will be 3) n
with 3. We see all go well, and when we compare 1+1 is smaller than two, so we continue. Next, we post increment i
to 2 but, as the post increment returns the value of i
before the increment, we reset i
to 1! (This is actually undefined behavior, but in your case you got this infinite loop.) Uh oh, that wasn't what we meant, so we fix this code to this:
for (i = 1; i + 1 < n; i++) {
if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1])
t = arr[i];
max.push_back(t);
}
The increment/decrement already modify int's value, which is why we don't need to assign it. Finally, we have to fix this error:
if (arr[1] < arr[0]) {
t = arr[0];
max.push_back(t);
count = 1;
}
This is a bit tricky, but the user might enter an number like 0, which would cause this to malfunction, while tricking the new
operator. To fix this, we can prevent this by replacing:
cin>>n;
With:
while (cin >> n && n < 1);
Which will read into n while n is less than 1;
Also, the reason I used new
is because it is what you use for dynamic allocation, or variable sized arrays. This allocates it:
int* arr = new int[n];
and this deallocates it:
delete[] arr;
For more info, read on pointers. Final Result:
#include <string>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, i, t, count, x;
count = 0;
cout << "Enter No of Elements";
while (cin >> n && n < 1);
int* arr = new int[n];
for (i = 0; i < n; i++)
{
cin >> arr[i];
}
vector<int> max;
max.reserve(n);
if (arr[1] < arr[0]) {
t = arr[0];
max.push_back(t);
count = 1;
}
for (i = 1; i + 1 < n; i++) {
if (arr[i] > arr[i - 1] && arr[i] > arr[i + 1])
t = arr[i];
max.push_back(t);
}
if (arr[n - 1] > arr[n - 2]) {
t = arr[n - 1];
max.push_back(t);
}
for (i = 1; i < max.size(); i++)
{
if (max[i] > max[i - 1])
count++;
}
cout << count;
cin >> x;
return 0;
}
Also, I initialized count
, because it was only being initialized in the if
.
Note: Quoting @user4581301
note on the use of new here. Prefer std::vector
when you need a dynamic array. std::vector automates the allocation and deallocation with RAII so you can be sure you have no leaks.