SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Michael T. Goodrich, Roberto Tamassia, Michael H. Goldwasser
Chapter:
Java Primer
Exercise:
Exercises
Question:15 | ISBN:9781118771334 | Edition: 6

Question

Write a pseudocode description of a method for finding the smallest and largest numbers in an array of integers and compare that to a Java method that would do the same thing.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

pseudocode:

        initialize array with random numbers
        
       step 1: initilize smallestNumber and largestNumber point to zeroth index
       as smallestNumber = array[0]
        largestNumber = array[1]

       step 2: run array thruogh for loop()
       step 3: update smallestNumber and largestNumber in each loop
        like if array[i] > largest
        set largest to array[i]
        
        if array[i] < smallest
        set smallest to array[i]

       step 4:  print(smallest, largest)

 

// Java code for the same

package java_problems_datastructures;

public class SmallestAndLargestNumber {
    
    // Driver method
	public static void main(String args[]) {

        // declare an array
		int[] arrayOfIntegers = { 234, 34, 45, 243, 545,-89, 54, 890, 3434, 9, 9843, 5, 453 };
        // call the method
		smallestAndLargest(arrayOfIntegers);

	}

	private static void smallestAndLargest(int[] array) {
        // point both values to first index of the array
		long smallestNumber = array[0];
		long largestNumber = array[0];

		for (int i = 1; i < array.length; i++) {

            // if we find smaller/greater than that, update the variable
			if (array[i] <= smallestNumber)
				smallestNumber = array[i];
			else if (array[i] >= largestNumber)
				largestNumber = array[i];

		}
        // print both values
		System.out.print("smallest number is: " + smallestNumber + "\n");
		System.out.print("largest number is: " + largestNumber);

	}

}

Output:

smallest number is: -89
largest number is: 9843

 

0 0

Discussions

Post the discussion to improve the above solution.