can anyone help me here?

is there any chance to shorten this code? " {
largest = a;
smallest = b;
} " i will paste my codes below

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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
  #include <iostream>
#include <stdio.h>
using namespace std;
int main ()
{
	int a,b,c,d,e,f,g,h;
	int largest, smallest;
	cout<<"Enter a 1st number ";
	cin>>a;	
	cout<<"Enter a 2nd number ";
	cin>>b;	
	cout<<"Enter a 3rd number ";
	cin>>c;	
	cout<<"Enter a 4th number ";
	cin>>d;	
	cout<<"Enter a 5th number ";
	cin>>e;	
	cout<<"Enter a 6th number ";
	cin>>f;	
	cout<<"Enter a 7th number ";
	cin>>g;	
	cout<<"Enter a 8th number ";
	cin>>h;	
	if (a>b)
	{
		largest = a;
		smallest = b;
	}
	else 
	{
		largest = b;
		smallest = a;
	}
	if (largest < c)
	{
		largest = c;
	}
	if (largest < d)
	{
		largest = d;
	}	
	if (largest < e)
	{
		largest = e;
	}	
	if (largest < f)
	{
		largest = f;
	}	
	if (largest < g)
	{
		largest = g;
	}	
	if (largest < h)
	{
		largest = h;
	}	
	if (smallest > c)
	{
		smallest = c;
	}
	if (smallest > d)
	{
		smallest = d;
	}	
	if (smallest > e)
	{
		smallest = e;
	}
	if (smallest > f)
	{
		smallest = f;
	}
	if (smallest > g)
	{
		smallest = g;
	}
	if (smallest > h)
	{
		smallest = h;
	}
		
	cout<<"The largest is "<<largest;
	cout<<"\n";
	cout<<"The smallest is "<<smallest;

	
	return 0;
}
Well, you only need to use three variables.
1
2
3
    int a;    // current number
    int largest;
    int smallest;


And instead of lots of similar-looking cin and cout statements, use a loop. Have you learned about loops yet? (You will need another variable to control the counting of the loop).
See tutorial:
http://www.cplusplus.com/doc/tutorial/control/
Last edited on
I guess it will be shorter one.

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

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

...

vector<int> total_sequence;
int curr_num;

while(cin >> curr_num) {
  total_sequence.push_back(curr_num);
}

if (total_sequence.size() == 0)
    return 0;

sort(begin(total_sequence), end(total_sequence));

cout << "The largest " << total_sequence[total_sequence.size() - 1] << endl
       << "The smallest " <<  total_sequence[0] << endl;

....
Last edited on
Registered users can post here. Sign in or register to post.