Reputation: 43
#include <iostream>
using namespace std;
int main()
{
int num1,num2,num3,num4;
int x;
int y;
cin>>num1>>num2>>num3>>num4;
if (num1 > num2)
{
x=num1;
}
else
{x = num2;
}
if(num3>num4)
{y = num3;
}
else
{
y= num4;
}
if (x>y)
{cout<<"the largest number is:"<<x;
}
else
{
cout<<"the largest number is :"<<y;
}
return 0;
}
this is my code to print largest number out of 4 numbers. the question is that i am asked to optimize or compact the solution. i tried but could not find another way to write such program.Can any one help me to optimize the solution and make it better.. ignore syntax errors..
Upvotes: 1
Views: 341
Reputation: 1
Try this :)) in this case i do not use std library. Just use an if-else statement like below. if(a > b) then return a else b. Other case, we can create an array and request input to the user. First we set the first element in this array is MAX value. Use a loop and check. if current element is larger than MAX then we update the MAX value to the current value.
int maxOfTwoNumber(int a, int b){ return a>b? a : b; }
int maxOfFourNumber(int a, int b, int c, int d){
return maxOfTwoNumber(maxOfTwoNumber(a, b), maxOfTwoNumber(c, d));
}
Upvotes: 0
Reputation: 218343
Since C++11, you may directly do
const int biggest = std::max({num1, num2, num3, num4});
Upvotes: 1
Reputation: 44288
Could be as simple as this:
int max = std::max( std::max( num1, num2 ), std::max( num3, num4 ) );
Upvotes: 5
Reputation: 905
#include<iostream>
using namespace std;
int main() {
int x, m;
cin >> x;
m = x;
for (int i = 0; i < 3; ++i) {
cin >> x;
m = m > x ? m : x;
}
cout << "The largest number is: " << m << endl;
return 0;
}
Use loops.
Upvotes: 4
Reputation: 312404
One approach would be to store the values in an array and iterate over it:
int num[4];
cin >> num[0] >> num[1] >> num[2] >> num[3];
int max = num[0];
for (int i = 1; i < 4; ++i) {
if (num[i] > max) {
max = num[i];
}
}
cout << "The largest number is:" << max << endl;
Upvotes: 1