smallest and largest

out of 3 numbers, how would you write out code that defines which is smallest...and which is largest?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

int main ()
{
  int n1, n2, n3;

  cout << "Enter three numbers to compare them: ";
  cin >> n1 >> n2 >> n3;

int sum;
  sum = n1 +  n2 + n3;
  cout << "Sum is " << sum << endl;

int average;
average = n1 + n2 + n3 / 3;
cout <<"Average is " << average << endl;

int product;
product = n1 * n2 * n3;
cout << "Product is " << product << endl;

int smallest;
  if(n1 < n2 || n3)
    cout << "Smallest is " << n1 << smallest;

    if(n2 < n1 || n3)
    cout << "Smallest is " << n2 << smallest;

    if(n3 < n2 || n1)
    cout << "Smallest is " << n3 << smallest;


int smallest is suppose to display the smallest of the 3 numbers
Last edited on
You dont need int smallest.

Here's how i would do it for smallest, and im sure you can figure out largest just from seeing this.
1
2
3
4
5
6
7
8
9
if( n1 < n2 && n1 < n3 )
{
     cout << "...." << n1;
}
else if( n2 < n1 && n2 < 3 )
{
     cout << "..." << n2
}
...
Last edited on
if(n1 < n2 || n3)

This won't work, because the compiler thinks you mean "OR if n3 is true," which is useless in a situation like this. In order for it to work, you'll need to expand each condition out like this:

if(n1 < n2 || n1 < n3)
if(n1 < n2 || n3) I'm 100% sure that is not what you want to do, more explicitly put, it reads if((n1 < n2) || n3) which is to say that if n1 is smaller then n2, the expression is true, or if n3 is true (n3 is not 0), the expression is true. So for what you have, as long as n3 is not 0, it will always evaluate to true. What you want is more along the lines of if(n1 < n2 && n1 < n3).

Moving along further, might I present my solution for finding the smallest, using a variable to hold the smallest:
1
2
3
4
5
6
{
   int smallest = n1;
   if(smallest > n2) smallest = n2;
   if(smallest > n3) smallest = n3;
   std::cout << smallest << std::endl;
}

I'm sure you can from here, figure out how to check for the largest.
Topic archived. No new replies allowed.