Thread: Print integers in descending order

  1. #1
    Registered User
    Join Date
    Dec 2021
    Posts
    1

    Print integers in descending order

    Code:
    #include <stdio.h>
    int main()
    {
    int a,b;
    scanf("%d %d",&a,&b);
    printf("%d %d",(a>b)? a,b:b,a);
    return 0;
    }

    My objective was not to use if,else
    Sample 1:
    input output
    1    2 

    2 1
    When the first integer is smaller the program works fine
    Sample 2;
    input output
    2    1

    1 2
    When the first integer is greater than the second ,the output is wrong (it doesn't print in descending order)
    From what I've understood ,I think that the Program only prints the false condition.
    Please help and fix this program. Thanks




  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,121
    I would suggest you do
    Code:
    if ( a < b ) {
      printf("%d %d",a,b);
    } else {
      printf("%d %d",b,a);
    }
    Because your way is a mess.
    Code:
    printf("%d %d",(a>b) ? a : b, (a>b) ? b : a);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Sep 2020
    Posts
    136
    My objective was not to use if,else
    What's wrong with that? It's easy to write and understand.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 3
    Last Post: 11-28-2017, 09:09 PM
  2. how to print scores in descending order
    By ingeniousreader in forum C Programming
    Replies: 5
    Last Post: 03-05-2012, 06:52 PM
  3. three numbers in descending order
    By jackson6612 in forum C++ Programming
    Replies: 3
    Last Post: 05-21-2011, 08:05 AM
  4. Replies: 9
    Last Post: 04-01-2011, 04:13 PM
  5. ascending and descending order
    By ssk in forum C Programming
    Replies: 3
    Last Post: 03-25-2011, 08:03 PM

Tags for this Thread