Jump to content

Check out our Community Blogs

Recent Status Updates

View All Updates

Developed by TechBiz Xccelerator
- - - - -

Smalles and largest of 5 integers?

  • Please log in to reply
4 replies to this topic

#1 Coldhearth


    CC Resident

  • Just Joined
  • PipPipPipPip
  • 88 posts

Posted 08 November 2009 - 04:44 AM


I'm studying java from the book Deitel: Java how to program 6th edition and I'm doing exercise 2.24 wish is:

Write an application that reads five integers, determines and prints the largest and smallest
integers in the group. Use only the programming techniques you learned in this chapter.

I was going to do it with Math.min en Math.max but that's not allowed.
Can someone help me out with if/else lusses for this one? :)
Cause I haven't got a good idea on how to solve this one...
  • 0

#2 wim DC

wim DC


  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 2675 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Python

Posted 08 November 2009 - 05:28 AM

if you have an array of 5 ints : int[] intArray = new int[5]
where those 5 integers are in.
then all you need is 2 more ints : max and min.
give max and min the value of the first int in the array.
for loop trough the array.
if(intArray[i]<min) min = intArray[i];
if(intArray[i]>max) max = intArray[i];
after the for loop they should have the right value.
  • 0

#3 Coldhearth


    CC Resident

  • Just Joined
  • PipPipPipPip
  • 88 posts

Posted 08 November 2009 - 05:48 AM

Yes but it's just the first chapter of the book so no arrays... just if and else...
  • 0

#4 WingedPanther73


    A spammer's worst nightmare

  • Moderator
  • 17725 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 08 November 2009 - 05:57 AM

Use five variables plus min/max and the same logic.
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/

#5 chili5


    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3034 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 08 November 2009 - 05:58 AM

Maintain two variables nSmall = Integer.MAX_VALUE and nMax = -1 and in the loop

for (int i=0;i<5;i++) {
      nNum = fin.nextInt();
      if (nNum > nMax) {
               nMax = nNum;

      if (nNum < nSmall) nSmall = nNum;

That is how I would do it. You could use Math.min and Math.max to avoid the if structures though.

Now, hopefully you will find this interesting (even though your book hasn't gotten to arrays yet). If you load the 5 integers into an array and sort the array, the smallest item is located at index 0 and the largest is located at n-1.
  • 0