I do not understand what is going on on variable k. For example I tried to put 1, 2, 3, 4, 5 but k shows me 1.
int a[5];
for (int i = 0; i < 5; i++) {
cin >> a[i];
}
int k = 0;
for(int j = 0; j < 5; j++) {
k += a[j] > a[j+1];
}
cout << k;
k shows a value of one because you are accessing out of bounds array a.
When j = 4, j+1 is 5 and so you are trying to access a[5] which is out of bound.
Hence it is incorrectly showing that a[j] > a[j+1] for one value. This is undefined behaviour.
Change your code to:
for(int j = 0; j < 4; j++) {
k += a[j] > a[j+1];
}
Now k will have a value of 0 if the input series is 1, 2, 3, 4 and 5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With