second highest number find by loops

Dec 27, 2018 at 8:22pm
Hi,
i made this program by loops to found second highest number and highest number from the inputs which user inputs.there are some issue i can not locate the problem please help me....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
main()
  {
	int n,i,j,marks,high,sec_high;
	high=sec_high=0;
	cout<<"Enter the numbers of students in class:";
	cin>>n;
	for(i=1;i<=n;i++)
	{
	cout<<"Enter the marks of students:";
	cin>>marks;
	if(marks>high)
	{
	sec_high=high;
	high=marks;
   }
	else if(sec_high<marks)
	sec_high=marks;
	cout<<"The highest marks is:"<<high<<endl;
	cout<<"The second highest marks is:"<<sec_high<<endl;
	getch();
   }
}
Last edited on Dec 27, 2018 at 8:23pm
Dec 27, 2018 at 9:23pm
what is it not doing right?

Dec 28, 2018 at 2:18am
//You need to add header files and namespace
#include <iostream>
using namespace std;

main()
{
int n,i,j,marks,high,sec_high;
high=sec_high=0;
cout<<"Enter the numbers of students in class:";
cin>>n;
for(i=1;i<=n;i++)
{
cout<<"Enter the marks of students:";
cin>>marks;
if(marks>high)
{
sec_high=high;
high=marks;
}
else if(sec_high<marks)
sec_high=marks;
cout<<"The highest marks is:"<<high<<endl;
cout<<"The second highest marks is:"<<sec_high<<endl;

//getch(); This is an old function, perhaps not supported by your compiler
getchar();
}
}
Dec 28, 2018 at 2:20am
I changed your program a bit and slightly restructured/reformatted it to make it compile. Notice that I changed it to from sec_high < marks to marks >= sec_high (Keeping the logic the same) -- I did not change the logic, but I just felt this was more consistent; first you were comparing against the highest, then you were comparing against the second highest.

Once you properly indent your code, you'll see your issue almost immediately.
You have your getch() and print statements within the for loop. getch() isn't even a standard function, by the way.

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
#include <iostream>
using namespace std;

int main()
{
	int n, high, sec_high;
	high = sec_high = 0;
	cout << "Enter the numbers of students in class:";
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cout << "Enter the marks of students:";
		int marks;
		cin >> marks;
	    
		if (marks > high)
		{
			sec_high = high;
			high = marks;
		}
		else if (marks >= sec_high)
		{
			sec_high = marks;
		}
	        
		cout << "The highest marks is: " << high << endl;
		cout << "The second highest marks is: " << sec_high << endl;
	    
		getch();
	}
}


Move lines 18-20 (your post) outside of the for loop.
Last edited on Dec 28, 2018 at 2:24am
Dec 28, 2018 at 3:29pm
Thanks...But I have a question,that the high and sec_high values inputs and then the difference showed,probably i solve this problem like this logic but i want whole values input and then difference show??
Dec 28, 2018 at 4:00pm
cout << high-sec_high;
Topic archived. No new replies allowed.