making codes shorter

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
int n1, n2, n3, n4, n5;
int a, b, c, d, e;
    cout << "Enter 5 numbers:\n";
	cin>>n1>>n2>>n3>>n4>>n5;
		if(n1==n2 && n1==n3 && n1==n4 && n1==n5)
			cout<<"The numbers you have entered are equal! \n\n";
		else
		{
        if (n1 > n2)
				a = n1;
		else
				a = n2;
		if (n3 > n4)
				b = n3;
		else
				b = n4;
		if (n5 > a)
				c = n5;
		else 
				c = a;
		if (b > c)
				d = b;
		else 
				d = c;
		cout<<d<< " is  the highest number!\n\n";
		 }


is there anyway to shorten this code?? please help.. and how can i input multiple values with just one command line??
In the future, questions such as this are best asked (and answered) in the beginners forum.

The simplest way to shorten the code is to use vectors/arrays and loops.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
	int numbers[5];

	for(int i = 0; i < 5; i++)
	{
		cin >> numbers[i];
	}

	int highest = 0;

	for(int i = 0; i < 5; i++)
	{
		if(numbers[i] > highest)
		{
			highest = numbers[i];
		}
	}

	cout << highest << "is the highest";


smth like this. not sure if its shorter :P
Last edited on
it is.. i guess.. lol.. xD

tnx for the help..

but by any chance.. is there anyway to remake the original code with another formula but with the same output using (nested) if else??and how?

@pan.. sorry.. this will be the last..
Last edited on
@Breadman: please don't answer homework questions with working code.
He had it correct i just made it shorter
There is no need for two loops:
1
2
3
4
5
6
7
8
9
int highest=0;
int numbers[5];

	for(int i = 0; i < 5; i++)
	{
		cin >> numbers[i];
               if(numbers[i]>highest)highest=numbers[i];
	}
cout<<"highest = "<<highest<<endl;
Or just:
1
2
3
4
const int numberCount=5;
int numbers[numberCount];
for (int i=0;i<numberCount;i++)cin >> numbers[i];
cout<< "highest = " << *max_element(numbers,numbers+numberCount) << endl;
Topic archived. No new replies allowed.