Please help.. too many if statements??

#include <iostream>
#include <stdlib.h>
#include <algorithm>
using namespace std;

int main()
{
int num1 = 3, num2 = 6, num3 = 1;
using std::cout;
using std::min;
using std::max;
cout << max(max(num1, num2), num3);
cout << min(min(num1, num2), num3);

if ((num1 > num2) && (num1 > num3))
{
cout << "\t Number one is the Largest which is: " << num1 << endl;
}

if ((num2 > num1) && (num2 > num3))
{
cout << "\t Number two is the largest which is: " << num2 << endl;
}

if ((num3 > num1) && (num3 > num2))
{
cout << "\t Number three is the largest which is: " << num3 << endl;
}

if ((num2 < num1) && (num2 < num3))
{
cout << "\t Number two is the smallest which is: " << num2 << endl;
}

if ((num3 < num1) && (num3 < num2))
{
cout << "\t Number three is the smallest which is: " << num3 << endl;
}

if ((num1 < num2) && (num1 < num3))
{
cout << "\t Number one is the smallest which is: " << num1 << endl;
}

system("pause");
return 0;
}
What do you mean by "too many statements"?
I need to return value from that and call as input to another call
What are you trying to lean here? Because normally, in this sort of situation we would store our values in some kind of container and use standard library functions to get this information.

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
32
33
34
35
36
37
38
#include <vector>
#include <iostream>
#include <algorithm>

int main()
{
	// put all our values in a container
	std::vector<int> v = {3, 6, 1};

	for(size_t i = 0; i < v.size(); ++i)
		std::cout << "Position: " << i << " = " << v[i] << '\n';

	std::cout << '\n';

	// examine v from beginning to end returning an
	// iterator to the largest element
	auto found = std::max_element(v.begin(), v.end());

	if(found != v.end()) // v.end() is returned if vector is empty
	{
		// the position number (starting from zero!)
		auto index = std::distance(v.begin(), found);

		std::cout << "Position " << index << " is the largest which is " << *found << '\n';
	}

	// examine v from beginning to end returning an
	// iterator to the smallest element
	found = std::min_element(v.begin(), v.end());

	if(found != v.end()) // v.end() is returned if vector is empty
	{
		// the position number (starting from zero!)
		auto index = std::distance(v.begin(), found);

		std::cout << "Position " << index << " is the smallest which is " << *found << '\n';
	}
}
Position: 0 = 3
Position: 1 = 6
Position: 2 = 1

Position 1 is the largest which is 6
Position 2 is the smallest which is 1
Last edited on
Also, if you're compiler supports C++11 or C++14, you can pass multiple values to max...
cout << max({ num1, num2, num3 });

By making it an initializer list, it will just tell you which is greatest, no need to pass results or do any looking and checking.
Like mentioned by Galik with a good example, just use a built in container and let it do the work.
Topic archived. No new replies allowed.