1
\$\begingroup\$

I have this task to find whether 5 integers are ordered from the smallest to the largest or not.

Depending on the results, the program output should be "yes" or "no". No loops or arrays supposed to be used (according to the task). This is my solution, but it's 4 lines longer. Can anyone help me make this better?

int main() {
    int a, b, c, d, e;

    scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);

    if ( a < b && b < c ) {
        if ( c < d && d < e ) {
            printf("yes");
        } else {
            printf("no");
        }
    } else {
        printf("no");
    }       

    return 0;
}
\$\endgroup\$
1
  • \$\begingroup\$ Don't forget to add the proper #include. You could also terminate the strings to be printed with a '\n' for proper line handling :) \$\endgroup\$ Commented Aug 2, 2014 at 11:31

3 Answers 3

3
\$\begingroup\$

Hint: think about whether you can combine the two if statements into one.

\$\endgroup\$
1
  • \$\begingroup\$ thnx. I just didn't realise that you can put all 4 conditions in one line :P \$\endgroup\$ Commented Aug 2, 2014 at 11:42
2
\$\begingroup\$

You can write the conditions in one line. For example

#include <stdio.h>

int main() 
{
    int a, b, c, d, e;

    scanf("%d %d %d %d %d", &a, &b, &c, &d, &e);

    if ( a <= b && b <= c && c <= d && d <= e ) 
    {
        printf( "Yes\n" );
    } 
    else 
    {
        printf("No\n");
    }       

    return 0;
}

If you need to check that the numbers are strictly sorted then remove sign = from the condition

\$\endgroup\$
3
  • 1
    \$\begingroup\$ At least it would be a good idea that there would be a comment why the answer is down voted. By the way I also can down vote answers. So the anonym take this into account. \$\endgroup\$ Commented Aug 2, 2014 at 12:06
  • 1
    \$\begingroup\$ I agree with you.ALL the answers in this question are downvoted in spite of them being perfectly valid. \$\endgroup\$ Commented Aug 2, 2014 at 12:10
  • \$\begingroup\$ Minor: Why use "%d %d %d %d %d" instead of "%d%d%d%d%d"? Readability? \$\endgroup\$ Commented Aug 4, 2014 at 22:18
1
\$\begingroup\$

To shorten it even more:

...

printf("%s\n", (a <= b && b <= c && c <= d && d <= e) ?"yes :"no");

...

Or take the recursive approach.

This example works for all i > 0:

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

int sorted(size_t n)
{
  int i;
  scanf("%d", &i);

  return ((i > 0 ) && ((n == 0) || (i <= sorted(n - 1)))) ?i :0;
}

int main(int argc, char ** argv)
{
  printf("%s\n", ((argc <= 1) || (0 < sorted(atoi(argv[1])))) ?"yes" :"no");
}

Pass the number of integers to be compared -1 on the command line, like this

$ ./a.out 4
\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.