second highest number find by loops

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
what is it not doing right?

//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();
}
}
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
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??
cout << high-sec_high;
Topic archived. No new replies allowed.