Finding the lowest and largest number in a nested loop [duplicate] - java

This question already has answers here:
Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array
(3 answers)
Closed 2 years ago.
int smallest = 0;
int largest = 0;
int num;
for (int row=1; row<=5; row++)
{
System.out.println();
System.out.println("Grades for student #" + row);
num = (int)(Math.random()*50)+50;
double total = 0;
smallest = num;
for (int col = 0; col<10; col++)
{
num = (int)(Math.random()*50)+50;
System.out.print(num+ ", ");
total += num*1.0;
}
System.out.println();
double average = total/10;
System.out.println("Average for student is " +
average);
if (num > largest) {
largest = num;
}
if (num < smallest) {
smallest = num;
}
}
System.out.println("The largest score is:" + largest);
System.out.println("The smallest score is : " +
smallest);
Trying to figure print out the lowest and largest score for random numbers generated in a loop for 5 students. The code is printing out the wrong number for lowest score.

The smallest and largest number are initialized with 0. They should be initialized with the first value instead.

You should put this part inside the nested loop.
if (num > largest) {
largest = num;
}
if (num < smallest) {
smallest = num;
}
Otherwise they are only comparing num of the last column of each row.

below is a code snippet of finding the largest and smallest value from a loop.you may adjust it with your requirement.
int minMax = 0;
int smallest = 0;
int largest = 0;
for(int i = 1; i <= totalNumbers; i++){
System.out.print("Number " + i + ": ");
int inputNumbers = console.nextInt();
if(inputNumbers > largest){
largest = inputNumbers;
} else if (inputNumbers < smallest){
smallest = inputNumbers;
}
}
System.out.println();
System.out.println("Smallest = " + smallest);
System.out.println("Largest = " + largest);

Related

Why am I not getting the minimum value in an array JAVA?

import java.util.*;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size ??");
int n = sc.nextInt();
int[] marks = new int[n + 1];
for (int i = 0; i < n; i++) {
System.out.println("Enter " + i + " number ??");
marks[i] = sc.nextInt();
}
System.out.println("The following numbers are : ");
for (int j = 0; j < marks.length - 1; j++) {
System.out.println(marks[j] + " ");
}
int max = marks[0];
int min = marks[0];
int s = marks.length;
for (int i = 0; i < s; i++) {
if (marks[i] > max) {
max = marks[i];
}
if (marks[i] < min) {
min = marks[i];
}
}
System.out.println("Max is " + max + " Min is " + min);
}
Output:
Enter the size ??2
Enter 0 number ??
56
Enter 1 number ??
56
The following numbers are :
56
56
Max is 56 Min is 0
Hello and welcome to StackOverflow. Next time, febore you jump into the internet for help, please try this approach. It will solve your problem much quicker.
for (int i = 0; i < s; i++) {
System.out.println("DEBUG: number in index " + i + " is " + marks[i]);
if (marks[i] > max) {
System.out.println("DEBUG: number is greater than current max " + max);
max = marks[i];
}
if (marks[i] < min) {
System.out.println("DEBUG: number is smaller than current min " + min);
min = marks[i];
}
}
This process is called "debugging". It can be done by adding spurious amount of logging like above or by stepping through the code with a debugger.
The size of mark array is 3 in the above example
int[] marks = new int[n + 1];
Let total number of marks is (n) : 2
We are creating the array with size of 3.
By default value for int primitives in java is 0
marks array is created with size 3
{56, 56, 0}
As per the logic the minimum value among these three elements are 0

How to display the highest and lowest numbers input by the user?

The program asks the user to input any amount of people they want. The program will then ask for the height of each person (not in feet, just in whole numbers like 5, 7, 10, etc.). The program then displays the average height of all those people as well as the tallest and shortest height out of those people.
The average height part works but my problem is trying to display the tallest height entered and shortest height entered.
package loop2;
import java.io.Reader;
import java.text.DecimalFormat;
import java.util.Random;
import java.util.Scanner;
public class PgmTemplate {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
int sum =0;
int number=0, n;
int average = 0;
int highest= 0;
int lowest= 0;
lowest = number;
System.out.println("enter the number of people");
n = input.nextInt();
for(int i = 0; i < n; i++) {
System.out.println("enter the height of each person");
number = input.nextInt();
sum += number;
average = sum / n;
}
if(number > highest) {
highest = number;
}else if(number < lowest) {
lowest = number;
}
System.out.println("the average height is "+ average);
System.out.println("the tallest person is " + highest);
System.out.println("the shortest person is " + lowest);
}
}
No need to calculate the average after every input.
I would do it like this:
lowest = Integer.MAX_VALUE
...
for (int i = 0; i < n; i++) {
int number = scanner.nextInt();
sum += number;
if (number > highest)
highest = number;
if (number < lowest)
lowest = number;
}
Then after getting all the input, you have what you need:
System.out.println("the average height is " + (sum / n));
System.out.println("the tallest person is " + highest);
System.out.println("the shortest person is " + lowest);
You need to put those checks between number, highest and lowest inside the loop.
As it stands you're only checking for the latest number that has been input.
Also you don't need to calculate a running average. So, move that outside the loop.
for (int i = 0; i < n; i++) {
System.out.println("enter the height of each person");
number = input.nextInt();
sum += number;
if (number > highest) {
highest = number;
} else if (number < lowest) {
lowest = number;
}
}
average = sum / n;

How to understand why this does not return the minimum value?

Please help to understand why, in the following, I didn't get output of minimum value in array. Using scanner for input value, the program should output also the minimum number.
** without using .sort.
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] list;
list = new int[10000];
int sum = 0;
double avr = 0;
int min = list [0];
int max = list [0];
int x = 0;
int value;
Scanner input = new Scanner(System.in);
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
while (x <= list.length && (value != -1 || x == 0)) {
list[x] = value;
x++;
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
}
for (int i = 0; i < list.length; i++) {
sum += list[i];
avr = sum / x;
if(list[i] > max)
max = list[i];
if( list[i] < min )
min = list[i];
}
System.out.println("The sum of all values are: " + sum);
System.out.println("The average value of the numbers are: " + avr);
System.out.println("The maximum value of the numbers are: " + max);
System.out.println("The minimum value of the numbers are: " + min);
}
}
I will suggest two improvements at the bare minimum.
Initialize your min to the first value. Right now you have min initialized to 0 and user never enters any number smaller than 0. That's why you keep getting 0 for min.
Don't run your loops 1000 times. Run it as many times as there are non zero elements.
See the following working snippet:
int[] list;
list = new int[10000];
int sum = 0;
double avr = 0;
int min = list [0];
int max = list [0];
int x = 0;
int value;
Scanner input = new Scanner(System.in);
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
min = value;
while (x <= list.length && (value != -1 || x == 0)) {
list[x] = value;
x++;
System.out.print("Add number " + (x + 1) + ": ");
value = input.nextInt();
}
for (int i = 0; i < list.length && list[i] !=0; i++) {
sum += list[i];
avr = sum / x;
if(list[i] > max)
max = list[i];
if( list[i] < min )
min = list[i];
}
System.out.println("The sum of all values are: " + sum);
System.out.println("The average value of the numbers are: " + avr);
System.out.println("The maximum value of the numbers are: " + max);
System.out.println("The minimum value of the numbers are: " + min);

How to get minimum and maximum individually and not as a whole?

Program does this:
Check if the max and min changes over the whole course of runs, and then prints them to the respective variables after each instance is complete based on user input.
But what I want it to do is:
Check the max and min for each individual run, then print them to the respective variables.
How can I change the code below so that it gets the max and min of each run instead of the overall max and min?
Here is the code:
package test;
import java.util.*;
public class Test {
public static void main(String[] args) {
Random generator = new Random();
float smallest, largest;
int years;
float[] array = new float[12];
smallest = Integer.MAX_VALUE;
largest = Integer.MIN_VALUE;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter desired years: ");
years = keyboard.nextInt();
for (int i = 1; i <= years; i++){
System.out.println("Year " + i);
for (int month = 1; month <= array.length; month++){
array[i] = generator.nextFloat() * 100;
System.out.println("Month " + month + ": " + array[i]);
if(array[i] < smallest)
smallest = array[i];
if(array[i] > largest)
largest = array[i];
}
System.out.println("Max = " + largest);
System.out.println("Min = " + smallest);
}
You aren't resetting largest and smallest at the end of the loop.
package test;
import java.util.*;
public class Test {
public static void main(String[] args) {
Random generator = new Random();
float smallest, largest;
int years;
float[] array = new float[12];
smallest = Integer.MAX_VALUE;
largest = Integer.MIN_VALUE;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter desired years: ");
years = keyboard.nextInt();
for (int i = 1; i <= years; i++) {
System.out.println("Year " + i);
for (int month = 1; month <= array.length; month++) {
array[i] = generator.nextFloat() * 100;
System.out.println("Month " + month + ": " + array[i]);
if (array[i] < smallest)
smallest = array[i];
if (array[i] > largest)
largest = array[i];
}
System.out.println("Max = " + largest);
System.out.println("Min = " + smallest);
// HERE
// Reset largest and smallest
largest = Integer.MIN_VALUE;
smallest = Integer.MAX_VALUE;
}
}
}

Why does my code output ridiculous numbers with the provided set? I'm trying String.format

I am using these numbers: 5,4,3.5,10,20,40,80,93.33,-1. It will work with something simple with only 5 numbers like: 5,4,3,2,1. What is going on? I am trying to use String.format to shorten the number if that is the issue. Do you guys notice anything within my code that I could do differently to maybe avoid this. This is the output with the provided set:
The minimum is -1.0, the maximum is 2.147483647E9, and the average is 2.38609322E8
-238609317.00
-238609318.00
1908874325.00
-238609312.00
-238609302.00
-238609282.00
-238609242.00
-238609229.00
-238609323.00
Desired Output
The Minimum is 3.5, The maximum is 93.33, and the average is 31.978749999999998
Score 5.0 is -26.978749999999998 from the average
Score 4.0 is -27.978749999999998 from the average
Score 3.5 is -28.478749999999998 from the average
Score 10.0 is -21.978749999999998 from the average
Score 20.0 is -11.978749999999998 from the average
Score 40.0 is 8.021250000000002 from the average
Score 80.0 is 48.02125 from the average
Score 93.33 is 61.35125 from the average
public static void main(String[] args)
{
int count = 0;
int arrayLength;
double min = 99999;
double max = 0;
double average;
double sum = 0;
JOptionPane.showMessageDialog(null, "This program will display the average as well as each numbers distance from the average");
// need to put loop here.
arrayLength = IO.readInt("How many numbers will you be entering?");
if (arrayLength <= 0 || arrayLength > 100)
{
JOptionPane.showMessageDialog(null, "Nothing entered, program will close.");
System.exit(0);
}
double[] array = new double[arrayLength];
for (int i = 0; i <arrayLength; i++)
{
array[i] = IO.readInt("Enter number: " + (i+1));
count++;
}
for (int i = 0; i <arrayLength; i++)
{
sum = (array[i] + sum);
if (array[i] <= min)
{
min = array[i];
}
if (array[i] > max)
{
max = array[i];
}
}
average = (sum / arrayLength);
System.out.println("The minimum is " + min + ", the maximum is " + max + ", and the average is " + average);
double[] array2 = new double[arrayLength];
for (int i = 0; i <arrayLength; i++)
{
array2[i] = (array[i] - average);
}
for (int i = 0; i <arrayLength; i++)
{
System.out.println(String.format("%.2f", array2[i]));
}
}
I don't know what happens when you do IO.readInt and put it into a double, but it isn't liable to be what you want...

Categories