Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

integer comparison incorrect or not comparing

Tags:

c++

arrays

int

I have an array as such:

int array[] = { 1,3,2,5,4,7,6,9,8,10 };

When I try to step through the array and compare the numbers none of them trigger the if condition thereby triggering the swap:

for( int i=0; i<9; i++)
{
    if (array[i] > array[i++])
    {
    cout << "Swapping" << array[i] << " " << array[i++]<< endl;
    int temp = 0;
    temp = array[i];
    array[i] = array[i++];
    array[i++] = temp;
    temp = 0;
}

}

Is there some detail of comparing integers that I am missing? Are they treated differently because they are in an array?

like image 352
Sion Avatar asked Aug 29 '26 00:08

Sion


1 Answers

i++ means "return i and set i = i + 1". So each time you're using i++ you are increasing i by one which ruins the loop. use i+1 instead.

like image 168
Ran Avatar answered Aug 30 '26 15:08

Ran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!