2

Hey So I am learning basic c++ just started this week, I have a question that says:

Write a program to compare 3 integers and print the largest, the program should ONLY Use 2 IF statements.

I am not sure how to do this so any help would be appreciated

So far I have this:

#include <iostream>

using namespace std;

void main()
{
int a, b, c;

cout << "Please enter three integers: ";
cin >> a >> b >> c;

if ( a > b && a > c) 
    cout << a;
else if ( b > c && b > a)
    cout << b;
else if (c > a && c > b)
    cout << b;

system("PAUSE");

}
TAM
  • 347
  • 4
  • 9
  • 20

4 Answers4

6
int main()
{
  int a, b, c;
  cout << "Please enter three integers: ";
  cin >> a >> b >> c;
  int big_int = a;

  if (a < b)
  {
      big_int = b;
  }

  if (big_int < c)
  {
    big_int = c;
  }
  return 0;
}

Also note, you should write int main() instead of void main().

billz
  • 44,644
  • 9
  • 83
  • 100
6
#include <iostream>

int main()
{
    int a, b, c;
    std::cout << "Please enter three integers: ";
    std::cin >> a >> b >> c;

    int max = a;
    if (max < b)
        max = b;
    if (max < c)
        max = c;

    std::cout << max;    
}

Although the above code satisfies the exercise question, I thought I'll add a couple of other ways to show ways of doing it without any ifs.

Doing it in a more cryptic, unreadable way, which is discouraged, would be

int max = (a < b) ? ((b < c)? c : b) : ((a < c)? c : a);

An elegant way would be to #include <algorithm> and

int max = std::max(std::max(a, b), c);

With C++11, you can even do

const int max = std::max({a, b, c}); 
legends2k
  • 31,634
  • 25
  • 118
  • 222
3

You don't need the last "else if" statement. In this part of code it is sure that "c" is maximal - no number is larger.

Ivan Kuckir
  • 2,327
  • 3
  • 27
  • 46
1

Hint: one of your if statements is useless (actually, it introduces a bug because nothing will be printed if a, b and c are all equal).

Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69