How to do this program?

I am writing a program that has 3 numbers stored, it has to output the nos. in ascending order.

#include <stdio.h> int main() { int a = 3; int b = 1; int c = 0; if (a < b < c) { // for a printf("%d < %d < %d\n", a, b ,c); } else if (a < c < b) { // for a printf("%d < %d < %d\n", a, c, b); } else if (b < a < c) { // for b printf("%d < %d < %d\n", b, a, c); } else if (b < c < a) { // for b printf("%d < %d < %d\n", b, c, a); } else if (c < b < a) { // for c printf("%d < %d < %d\n", c, b, a); } else if (c < a < b) { // for c printf("%d < %d < %d\n", c, a, b); } }

but when i am running it, it shows the output 3 < 0 < 1
and that is not meant to happen!
i checked first else if line but could not find the problem.

pls help me

See this post. The post has to do with JavaScript but (almost) the same issue arises in C as well.

https://discuss.codecademy.com/t/when-should-i-use-multiple-if-statements-when-should-i-use-if-statements-with-else-if-statements/365545/30

If I am not mistaken, in C, if a comparison is true, it evaluates to 1. If false, it evaluates to 0.
In JavaScript, comparisons evaluate to boolean true/false and if needed are coerced to integers 1/0 respectively.
Other than that, your issue is the same as in the linked post.

You will have to use the && operator e.g.

if (a < b < c) # Doesn't do what you think
# Rewrite it as:
if ((a < b) && (b < c))

# Do similar rewrites of the else if statements

In the code in your post, this is what is happening :

int a = 3;
int b = 1;
int c = 0;

if (a < b < c)
# Since < operator has same precedence, so expression is 
# evaluated from left to right.
# a < b is 3 < 1 which results in 0
# 0 < c is 0 < 0 which results in 0
# If condition is false and we should move on.

else if (a < c < b)
# evaluated from left to right.
# a < c is 3 < 0 which results in 0
# 0 < b is 0 < 1 which results in 1
# else if condition is true and we print
printf("%d < %d < %d\n", a, c, b);
Output: 3 < 0 < 1 
1 Like