Home > Software engineering >  Not getting expected output in descending order
Not getting expected output in descending order

Time:10-31

#include <stdio.h>

int main(int argc, char *argv[])
{
    int a[4] = {20, 4, 7, 8};

    for (int i = 0; i < 4; i  )
    {
        for (int j = 0; j < 4; 
j  )
        {
           if (a[i] < a[j])
            {
                a[i] = a[j];
            }
        }
        printf("%d\n", a[i]);
        a[0] = 20;
        a[1] = 4;
        a[2] = 7;
        a[3] = 8;
    }
}

I simply trying to show the output as descending order but not getting expected result

Expected : 20 8 7 4

Error follows: 20 20 20 20

  • Please help me to rectify ..

CodePudding user response:

You aren't swapping a[i] with a[j], you're simply copying the value of a[j] to a[i].

To do a swap, you need three operations:

int tmp = a[i];  // save the value of a[i]
a[i] = a[j];     // write a[j] to a[i]
a[j] = tmp;      // write saved value of a[i] to a[j]
  •  Tags:  
  • c
  • Related