Basically, I have an array given of “x” numbers and I have to output the amount of how many times the sign changed in the numbers of the array.
For example array is:
2 -4 5 6 7 -2 5 -7
The output should be 5. Why? Because the sign changes first time at -4, second time at 5, third time at -2, fourth time at 5 and last time at -7. Total 5 times.
So, I have this so far but that doesn’t work perfectly:
#include <iostream>
using namespace std;
int main()
{
int a[50],n,cs=0,ha=0;
cin >> n;
for (int i=0;i<n;i++)
{
cin >> a[i];
}
for (int j=1;j<=n;j++)
{
if(a[j]<0 && a[j-1]>0)
cs++;
else if(a[j]>0 && a[j-1]<0)
cs++;
}
cout << cs << endl;
return 0;
}
Please help!
Your problem is that you’re running into uninitialized memory, which is causing undefined behaviour. You initialize
a[0]througha[n-1]in your input loop and then read froma[0](with j=1 anda[j-1]) toa[n](j=n anda[j]) in your calculation loop.Simply change it to
j < n.