Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the code in c++ mean?

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;
like image 302
Johny Avatar asked Apr 11 '26 09:04

Johny


1 Answers

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.

like image 163
Abhishek Bansal Avatar answered Apr 13 '26 00:04

Abhishek Bansal