Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Find 2nd Largest Integer using IF

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hi, if a user enters 7 integers. How do I find the second largest integer. Thanks
 
#define GET_MAX(X) if (X >=MAX1) Max1 = X;else if (X <MAX1 && X>=Max2) Max2 = X;

if (A >= B) {
Max1 = A; Max2 = B;
}else {
Max1 = B; Max2 = A;
}
GET_MAX(C)
GET_MAX(D)
GET_MAX(E)
GET_MAX(F)
GET_MAX(G)
 
hi, could you explain how that code works? I'm not understanding it's layout. Thanks
 
Assume Max1 and Max2 are the variables used to store the largest and the second largest integers.

first you compare A and B and put the bigger one into Max1 and the other one into Max2.
For the next integer C, compare it with Max1 and Max2. If C is no less than Max1, then C is the largest so far and Max1 is updated to C. Max2 stays unchanged. If C is less than Max1 but no less than Max2, then C is the second largest so far and Max2 is updated to C and Max1 stays unchanged. Otherwise if C is less than Max2, Max1 and Max2 keep unchanged.
Following the same logic with D to G, you will get the global largest and second largest Max1 and Max2.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top