Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not getting expected output in descending order

#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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • Please help me to rectify ..

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading