Friday, July 31, 2009

How to write a c program that chooses 3 out of 5 largest numbers?

Hi everyone! I was wondering if you could help me write this C program. I've spent a lot of time on it and I can't think of anything good. Hints would be appreciated as well :D





"Write a complete C program that will ask a user for 5 integer numbers and will print out on the screen the three largest. "





Thank you!

How to write a c program that chooses 3 out of 5 largest numbers?
no offense, but this is very basic. This has little to do with C language, you need to think on how to figure out which is the largest numbers. This is more of an exercise on how you can think logically than it is programming.





You need to do a comparison, and the largest number needs to be held and then compared against the others. Once you figure out the largest, you do a comparison with the 4 remaining, until you have the 3 largest.
Reply:I'll leave the actuall coding to you, but for the logic, you'll want to store them into an array of ints, run them through the sort routing of your choice (knowing it's only 5 elements means you can use any method, even the brute force methods, and it will be pretty cheap), then output elements 0-2 (or 2-4, depending on how you sort) of the array.
Reply:Define four integers. One for Input, a Largest, Second and Third.





I would initialize them all to zero because it's Hip, Modern, and you never know what garbage is lurking in your memory unless you watch old episodes of Reboot.





Repeat five times:





Get the Input number.





Compare it to Largest.





If Input is bigger than Largest


swap Third and Second


swap Largest and Second


swap Input and Largest


Else if Input is bigger than Second


swap Third and Second


swap Input and Second


Else if Input is bigger than Third


swap Input and Third


Else do nothing.





End Repeat five times.


Print Largest, Second and Third.


End program.


No comments:

Post a Comment