Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Integers C++ [closed]

Tags:

c++

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");

}
like image 275
TAM Avatar asked May 16 '26 01:05

TAM


2 Answers

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().

like image 144
billz Avatar answered May 19 '26 03:05

billz


#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}); 
like image 28
legends2k Avatar answered May 19 '26 04:05

legends2k



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!