2

I am making a code that will:

  1. print an array of random numbers
  2. order it to an ascending order
  3. find the odd numbers from that array
  4. arrange the odd numbers to a descending order.

I've done the first three but I can't arrange the odd numbers to a descending order. The program sorts the random numbers to a descending order instead of just the odd numbers. Please help me. Thank you.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    int size,i,j,temp;
    int a[50];

    printf("Enter array size| ");
    scanf("%i",&size);

    srand(time(0));

    printf("\nThe Random Numbers| \n");
    for(i=0;i<size;i++){
        a[i] = rand()%100;
        printf("%i, ",a[i]);
    }

    for (i=0;i<size;++i)
    {
        for (j=i+1;j<size;++j)
        {
            if (a[i]>a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }
    printf("\n\nThe Ascending Order of Random Numbers| \n");
    for (i=0;i<size;++i)
        printf("%d, ", a[i]);


    printf("\n\nThe Odd Numbers| \n");
    for(i=0;i<size;i++){
        if(a[i]%2!=0){
            printf("%i, ",a[i]);
        }
    }

    for(i=0;i<size;i++){
        for(j=i+1;j<size;j++){
            if(a[i]<a[j])
            {
                temp=a[i];
                a[i]=a[j];
                a[j]=temp;
            }
        }
    }

    printf("\n\nThe Descending Order of Odds| \n");
    for(i=0;i<size;i++)
        printf("%d ",a[i]);

    return 0;
}
dWinder
  • 11,597
  • 3
  • 24
  • 39
Luxe
  • 69
  • 1
  • 6

1 Answers1

2

Consider n to be array length -1 and look at the following pseudo code:

for each i in n {
      if a[i] even:
          continue
      for each j in n {
          if a[j] even:
              continue
          if(a[i]<a[j])
              swap(a[i], a[j])
      }
}

In this case you ignore the even number and modify only the array places who contains odd value.

This is c code:

for(i=0;i<size;i++){
    if(a[i]%2!=0) {
        for(j=i+1;j<size;j++){
            if((a[j]%2!=0) && (a[i]<a[j]))
            {
                t=a[i];
                a[i]=a[j];
                a[j]=t;
            }
        } // end of j for loop
    } // end of if odd
} // end of i for loop
dWinder
  • 11,597
  • 3
  • 24
  • 39