Question #805

I am writing a program that finds both the largest and smallest of several integers. These are the integers: 6 20 30 40 50 60 70. Assume that the first integer read specifies the number of values remaining to be entered and that the first number is not one of the integers to compare. Your program should read only one value per input statement. Where do I start?

Expert's answer

First thing is to specify 3 variables to store values - 'num' to store integers count, 'min' to store smallest value and 'max' to store largest.

After that you have this algorithm:

1. Read number of integers and store it; num = readInt().

2. Read next integer and assing it to largest and smallest variable, then decrease num variable; min = readInt(), max = min, num = num - 1.

3. Read next integer and compare it with largest and smallest;

temp = readInt()

if (temp > min) {

min = temp

}

if (max < temp) {

max = temp

}

4. Decrease 'num' variable. Exit form the programs, if it's equal to zero, or go to point 3 of the algorithm otherwise.

After that you have this algorithm:

1. Read number of integers and store it; num = readInt().

2. Read next integer and assing it to largest and smallest variable, then decrease num variable; min = readInt(), max = min, num = num - 1.

3. Read next integer and compare it with largest and smallest;

temp = readInt()

if (temp > min) {

min = temp

}

if (max < temp) {

max = temp

}

4. Decrease 'num' variable. Exit form the programs, if it's equal to zero, or go to point 3 of the algorithm otherwise.

## Comments

## Leave a comment