Johny
Johny

Reputation: 119

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;

Upvotes: 2

Views: 146

Answers (3)

Abhishek Bansal
Abhishek Bansal

Reputation: 12715

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.

Upvotes: 7

Tony Delroy
Tony Delroy

Reputation: 106096

The loop iterates over the array a, comparing a[0] > a[1], a[1] > a[2], a[2] > a[3] etc.. When a boolean is added to an integer, it's first converted to 0 (if false) or 1 (if true). So, k ends up being a count of the number of times an element if greater than the following element.

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490108

a[j] > a[j+1] produces a Boolean result (false or true). In an int context, true and false convert to 1 and 0 respectively.

So, this is roughly equivalent to:

for (int j=0; j<5; j++)
    if (a[j] > a[j+1])
        ++k;

Upvotes: 3

Related Questions