i'm nw with this subject so can anyone please help me to write a program that accepts three numbers as input, then sorts the three numbers and displays them in ascending order, from lowest to highest.
I assume that's his/her 1st assignment at C++. I don't wanna be rude, but you better download the cpp tutorial and start to read it, because next assignments will be harder
after you read the 1st few chapters, including data types, basic input/output operations and if/else construction (ca. 40 pages, not much) it won't be that hard to do it all by yourself.
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
int num1, num2, num3;
cout<<"Please enter first number : ";
cin>>num1;
cout<<"Please enter second number : ";
cin>>num2;
cout<<"Please enter third number : ";
cin>>num3;
if (num1 < num2 < num3)
{
cout<<"Numbers in ascending order : "<<num1<<" "<<num2<<" "<<num3<<endl;
}
else if (num1 < num3 < num2)
{
cout<<"Numbers in ascending order : "<<num1<<" "<<num3<<" "<<num2<<endl;
}
else if (num2 < num1 < num3)
{
cout<<"Numbers in ascending order : "<<num2<<" "<<num1<<" "<<num3<<endl;
}
else if (num2 < num3 < num1)
{
cout<<"Numbers in ascending order : "<<num2<<" "<<num3<<" "<<num1<<endl;
}
else if (num3 < num1 < num2)
{
cout<<"Numbers in ascending order : "<<num3<<" "<<num1<<" "<<num2<<endl;
}
else if (num3 < num2 < num1)
{
cout<<"Numbers in ascending order : "<<num3<<" "<<num2<<" "<<num1<<endl;
}
cout<<endl;
getche ();
return 0 ;
}
somehow, if i enter numbers, 1,8,4, the order will still be 1 8 4 rather than in ascending order.
if (num1 < num2 < num3) doesn't do what you are expecting, it evaluates num1 < num2 which can be 1 (true) or 0 (false) and then compares that value with 'num3'
You should use logical operators: if ( num1 < num2 && num2 < num3 )
or nesting: