I have an assignment where I am supposed to have 6 elements in an integer array and program supposed to find the highest and lowest element in an array and omit those two elements and find the average for the remaining four elements. So far my program is able to find the lowest and highest number in that array and able to omit it, however, I cant seem to save those results from the loop to a variable so I can start to calculate my average. the code is
int bucky[] = { 4, 6, 8, 19, 199, 400 };
int hello = 0;
int max = 0;
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] > max) {
max = bucky[i];
}
}
System.out.println("Max number is " + max);
int min = 0;
int j = 1;
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] < bucky[j]) {
min = bucky[i];
j = i;
}
}
System.out.println("min number is " + min);
System.out.print("{");
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] != max) {
if (bucky[i] != min) {
System.out.print(" " + bucky[i]);
}
}
}
System.out.print("}");
So far it prints out {6 8 19 199}. I want to be able to save them in a variable and calculate the average. Any help would be appreciated.
Here is a simple program that might achieve what you are after.
What should happen if all elements have the same value?
int[] input = {0,1,2,3,4,5};
int max = input[0];
int min = input[0];
int sum = 0;
for(int i : input){
sum += i;
if(i < min){
min = i;
}else if(i > max){
max = i;
}
}
System.out.println("sum for input is : " + sum);
System.out.println("highest value element is : " + max);
System.out.println("lowest value element is : " + min);
System.out.println("sum excluding extreme elements is : " + (sum - min -max));
// have cast the result as a float as i dont know if average should be truncated or not
System.out.println("average excluding extreme elements is : " + ((float)(sum - min -max)/(input.length-2)));
public static void main(String args []){
int bucky [] = new int [] {4, 6, 8, 19, 199, 400};
int max = bucky[0];
int min = bucky[0];
int sum = 0;
for(int i = 0; i<bucky.length; i++){
if(min > bucky[i]){
min = bucky[i];
}
else if(max < bucky[i]){
max = bucky[i];
}
sum += bucky[i];
}
sum -= (min + max);
System.out.println("Max is " + max);
System.out.println("Min is " + min);
System.out.println("Sum is " + sum);
System.out.println("Average is " + sum/(bucky.length-2));
}
Small program can be developed using arrays in Java as follows, which initially stores very first element of the array in min, max, and sum, then start traversing the array from first element and determine min and max value elements by comparing them with the current element pointed by input[i] of the array. Also add input[i] every time to the sum variable to get sum of all elements. After having computed min, max, and sum value elements; compute avg by subtracting min and max from sum and divide the resultant value by length - 2.
class ComputeAvg
{
public static void main (String[] a)
{
int[] input = {10,11,12,13,14,15};
int min, max, sum, avg;
min = max = sum = input[0];
int length = input.length;
for (int i = 1; i < length; i++)
{
if (min > input[i])
min = input[i];
else if (max < input[i])
max = input[i];
sum += input[i];
}
avg = (sum - min - max)/(length - 2);
System.out.println("sum for input is : " + sum);
System.out.println("highest value element is : " + max);
System.out.println("lowest value element is : " + min);
System.out.println("sum excluding min and max value elements is : " + (sum - min - max));
System.out.println("Average after excluding min and max value elements is : " + avg);
}
}
OUTPUT
======
sum for input is : 75
highest value element is : 15
lowest value element is : 10
sum excluding min and max value elements is : 50
Average after excluding min and max value elements is : 12
You're 90% there. You just need a nudge in the right direction.
You already know how to filter your results from highest and lowest with this statement (rewritten to compress nested ifs):
for(int i=0;i<bucky.length; i++){
if(bucky[i] != max && bucky[i] !=min) {
// implementation
}
}
By the way, it can be rewritten as this, thanks to De Morgan's Law. This may read more straightforward for you: "If the value in bucky[i] is neither max nor min..."
for(int i=0;i<bucky.length; i++){
if(!(bucky[i] == max || bucky[i] ==min)) {
// implementation
}
}
That was the hard part. What you now need:
A counter to tell you how many values you actually are adding. Something like adjustedTotal. You'd only ever add to this counter if the number wasn't the min or the max.
A simple sum variable, initialized appropriately, taking the values from bucky[i] such that bucky[i] != max && bucky[i] != min.
int sum=0;
for (int i=0 ;i< arr.length;i++) {
if(arr[i]!=max && arr[i]!=min) {
sum=sum+arr[i];
}
}
int average=sum/(arr.length-2)
You can define an variable named sum like Makoto mentioned above.
In additional, I would like to point out that there is something wrong with your code for calculating min.
Here is an example,
Assume the int[] array is as follows:
int bucky[] = { 6, 4, 8, 19, 400,199 };
Use your code below:
int min = 0;
int j = 1;
for (int i = 0; i < bucky.length; i++) {
if (bucky[i] < bucky[j]) {
min = bucky[i];
j = i;
}
}
System.out.println("min number is " + min);
What will be the value for min ?
It will be 0. It is incorrect.
You can first specify the first element in array as min, and then compare it with remaining values. If any value is smaller than min, then change the value for min.
Here is an example:
int min = bucky[0];
//int j = 1;
for (int i = 1; i < bucky.length; i++) {
if (bucky[i] < min) {
min = bucky[i];
}
}
System.out.println("min number is " + min);
Make some change and move on. :)
Related
I am trying to get the sum, average, max and min value from user input in array. sum, average and max is giving the correct output. But min value is not working. Where am I doing wrong would someone help me please to find out?
import java.util.Scanner;
public class minMaxSumAverage {
public static void main(String args[]) {
int n, sum = 0, max, min;
double average = 0;
Scanner s = new Scanner(System.in);
System.out.println("Enter elements you want to input in array: ");
n = s.nextInt();
int a[] = new int[n];
max = a[0];
min = a[0];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum += a[i];
average = (double) sum/a.length;
if (a[i] > max) {
max = a[i];
}
if (a[i] < min) {
min = a[i];
}
}
System.out.println("Sum is: " + sum);
System.out.println("Average is: " + average);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
}
Output:
Enter elements you want to input in array:
5
Enter all the elements:
25
5
10
6
4
Sum is: 50
Average is: 10.0
Max is: 25
Min is: 0
Min value should be 4.
I have updated you code. Please check following code to get min value from all element list.
Input :
Enter elements you want to input in array:
5
Enter all the elements:
25
5
10
6
4
Output :
Sum is: 50
Average is: 10.0
Max is: 25
Min is: 4
Scanner scan = null;
try {
int n, sum = 0, max, min;
double average = 0;
scan = new Scanner(System.in);
System.out.println("Enter elements you want to input in array: ");
n = scan.nextInt();
int a[] = new int[n];
max = a[0];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = scan.nextInt();
sum += a[i];
average = (double) sum/a.length;
if (a[i] > max) {
max = a[i];
}
/**
// from here remove logic for get min value.
if (a[i] < min) {
min = a[i];
}
**/
}
min = a[0];
for(int i=0;i<a.length;i++){
if(a[i] < min){
min = a[i];
}
}
System.out.println("Sum is: " + sum);
System.out.println("Average is: " + average);
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
catch (Exception ex) {
ex.printStackTrace();
}finally{
scan.close();
}
From Java-8 you can use streams to get this done in single line:
int[] a = new int[] { 20,11,2,3,4,7,8,90 };
int min = Arrays.stream(a).min().getAsInt();
for getting the maximum element, just replace the .min() with .max()
for getting sum: Arrays.stream(a).mapToInt(Integer::intValue).sum();
Because min is initialized with 0.
And in your loop you just ask if your current number is smaller than 0.
Try again with assigning the first value of your array as min.
Then it should work.
int a[] = new int[n];
max = a[0];
min = a[0];
You have created an empty array a. Both max and min are initialized to 0. This works fine for max, but gives you the result you are seeing for min, because there is nothing smaller in your created array than zero.
To fix this, add your line min = a[0]; into the for loop after you have filled up your array with values, e.g.
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
sum += a[i];
average = (double) sum/a.length;
min = a[0];
//if-statements here
Then, min = a[0] will no longer be zero, but will be the first value of the filled up array.
Please refer below code for a min, max, sum, average functionality :
List<Integer> intList= Arrays.asList(70, 80, 10, 20, 40, 50);
Integer ans=0;
int sum1= intList.stream().reduce(ans, (x,y) -> x+y);
System.out.println(sum1);
int sum2= intList.stream().reduce(ans, Integer::sum);
System.out.println(sum2);
int max= intList.stream().max(Integer::compare).get();
System.out.println(max);
int min= intList.stream().min(Integer::compare).get();
System.out.println(min);
Double avg= intList.stream().collect(Collectors.averagingInt(x-> x));
System.out.println(avg);
As an alternative, you may want to consider a Stream...
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter count elements you want to input in array: ");
int n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++) {
a[i] = s.nextInt();
}
s.close();
IntSummaryStatistics iss = Arrays.stream(a).summaryStatistics();
System.out.println("Sum is: " + iss.getSum());
System.out.println("Average is: " + iss.getSum()/iss.getCount());
System.out.println("Max is: " + iss.getMax());
System.out.println("Min is: " + iss.getMin());
}
I have some trouble when I try to code a program.
double max = 0, min = 0;
int i;
double array[] = new double[10];
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
When I type 10 numbers that include one largest number and one smallest number,
the result is
The Max is : largest number
The Min is : 0.0
Always the Smallest I get the 0.0 whatever I type. No 2 I will type, No 4 I will type as a smallest number (always on separate launch), every time I get 0.0.
Your initial value for minimum is zero, and I assume your data has nothing that is less than zero.
Try setting your min initial value to Double.MAX_VALUE
you Initializing max and min before entering number into the array , when tring to find the max and the min , first enter the numbers to the array then compare them with the array[0].
second thing is that you dont need to for loops to check whether you need to change max or min , you can do it in one for loop .
try this :
double array[] = new double[10];
int i;
Scanner input = new Scanner(System.in);
for (i = 0; i < 10; i++) {
System.out.println("Give the " + (i + 1) + " number");
array[i] = input.nextDouble();
}
double max = array[0], min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Two simple corrections:
You just have to set initialized min and max to some values in array. (e.g. array[0] for your problem)
there is no need to 3 for loops to find the min and max, just use one.
see below code:
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
System.out.println("Give the " + (1) + " number") ;
array[0] = input.nextDouble();
double max = array[0], min = array[0];
for (i = 1; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
if(array[i] > max)
max = array[i] ;
if (array[i] < min)
min = array[i];
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Your curly braces are not proper. You are ending the max loop before the SYSOUT.
double max = 0, min = 0;
int i;
double array[] = new double[10] ;
Scanner input = new Scanner (System.in) ;
for (i = 0; i < 10; i++)
{
System.out.println("Give the " + (i+1) + " number") ;
array[i] = input.nextDouble();
}
max = array[0];
min = array[0];
for (i = 0; i < 10; i++) {
if (array[i] > max) {
max = array[i];
}
}
for (i = 0; i < 10; i++) {
if (array[i] < min) {
min = array[i];
}
}
System.out.println("The Max is :" + max);
System.out.println("The Min is :" + min);
Run this. It will give the proper result.
What did I do wrong? I'm really not sure what else to try or where my mistake is. Thanks for any help. It's supposed to calculate the sum of integers between two numbers, e.g. between 3 and 6 it would be 3 + 4 + 5 + 6
import java.util.Scanner;
public class TheSumBetweenTwoNumbers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("First:");
int n = Integer.parseInt(reader.nextLine());
System.out.println("Second:");
int max = Integer.parseInt(reader.nextLine());
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
System.out.println("Sum is " + sum);
}
}
Why all this you need just a piece of code like this :
public static void main(String args[]) {
int min = 3, max = 6, sum = 0;
for (int i = min; i <= max; i++) {
sum += i;
}
System.out.println(sum);
}
With while loop it should be :
...
int i = min;
while (i <= max) {
sum += i;
i++;
}
...
You don't need to find a difference and loop over it, just running a loop from n to max will do. Also, you need to add the value to sum (+=) instead of assigning a value to it (=, which overwrites previous value)
Try this:
int i = n;
while (i <= max) {
sum += i;
i++;
}
You're overwriting the previous sum value with the most recent n + (n + 1), instead of accumulating the previous sum. Also, your loop is one iteration short. Try this:
int sum = 0;
for (int i = n; i <= max; i++) {
sum += i;
}
System.out.println("Sum is " + sum);
Change this snippet
int sum = 0;
int i = 0;
int difference = max - n;
while (i < difference) {
sum = n + (n + 1);
n++;
i++;
}
In
int sum = 0;
int i = n;
while (i <= max) {
sum = sum + i;
i++;
}
You made it a little bit overcomplicated. All you really need is a for loop that runs from n to max that adds up the incrementing variables:
int sum = 0;
for(int i = n; i <= max; i++){
sum += i;
}
I have made a loop that produces the sum and average of numbers 1,2,3,...,to an upperbound 100. What I am having trouble with is modifying my current code so it only includes numbers that are multiples of 7. Here is what I have:
public class SumAndAverageForLoop {
public void SumAndAverageForLoop() {
double sum = 0;
for (double i = 1; i <=100; i++) sum+= i;
System.out.println ("the average is " + sum/100);
System.out.println ("the sum is " + sum);
}
}
I am trying to do it without a main method so I had to create a Launcher class.
Any help is appreciated. Thank you in advance.
In order to determine if a number is divisible by 7 you should use the modulo devision operator % and compare the remainder to 0;
int sum = 0;
int count = 0;
for (int i = 0; i <= 100; i++) {
if (i % 7 == 0) {
sum += i;
count++;
}
}
System.out.println("the average is " + sum/count);
System.out.println("the sum is " + sum);
Also I wouldn't recommend using a double when all you need is an int. You might get caught out by precision issues further down the road. You could cast your sum to a double before dividing to by count if you want a decimal average. Like this:
System.out.println("the average is " + ((double) sum)/count);
In Java 8 this is now easily accomplished without writing error prone looping structures as follows:
IntStream.range(0,100).filter(i -> i % 7 == 0).summaryStatistics();
Result:
IntSummaryStatistics{count=15, sum=735, min=0, average=49.000000, max=98}
Your for loop should increment in 7's for each iteration and also you should maintain a count of your iterations because you need it for finding average.
int sum = 0;
int count = 0;
int average = 0;
for(int i=7; i<=100; i=i+7)
{
sum = sum + i;
count= count+1;
average = sum/count;
}
I would use the Modulus operator for this use case.
public class SumAndAverageForLoop {
public void SumAndAverageForLoop() {
double sum = 0;
for (double i = 1; i <=100; i++){
if((i % 7) == 0){
sum+= i;
}
System.out.println ("the average is " + sum/100);
System.out.println ("the sum is " + sum);
}
}
The problem im getting is that with oddSum the value outputted is the same as evenSum, and the value for sum of all elements is 0.
I cant quite see where im going wrong as the loops are pretty similar and if the even one works the others should too?
Here is my code anyway:
int evenData[] = new int [10];
int oddData[] = new int [10];
int sum = 0;
int evenSum = 0;
int oddSum = 0;
int[] data = {3, 2, 5, 7, 9, 12, 97, 24, 54};
for(int index = 0; index < data.length; index++)
{
if (data[index] % 2 == 0)
{
int temp = data[index];
data[index] = evenData[index];
evenData[index] = temp;
}
else
{
int temp = data[index];
data[index] = oddData[index];
oddData[index] = temp;
}
}
for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++)
{
evenSum =evenData[evenIndex] + evenSum;
}
System.out.print("Sum of even elements: " + evenSum);
for(int oddIndex = 0; oddIndex < oddData.length; oddIndex++)
{
oddSum = oddData[oddIndex] + oddSum;
}
System.out.print("Sum of odd elements: " + oddSum);
for(int index = 0; index < data.length; index++)
{
sum = data[index] + sum;
}
System.out.print("Sum of all elements: " + sum);
You are getting same value for even and odd because you are printing the same value: -
System.out.print("Sum of odd elements: " + evenSum);
Also, your final sum is zero because you are making out all the elements of your original array as zero, as you are swapping your elements with the elements in evenData and oddData, which are zero initially.
int temp = data[index];
data[index] = evenData[index]; // This code assigns a value 0 to current index.
evenData[index] = temp;
So, you are iterating your array, and assigning 0 to each of your index, while adding the previous element to the new array.
I would say that you are needlessly using 2 extra array and 3 extra loops. Why not just create a sum in the place where you are iterating your original array?
In fact, all your sums can be computed in a single loop: -
for(int index = 0; index < data.length; index++)
{
sum += data[index];
if (data[index] % 2 == 0)
{
// int temp = data[index];
// data[index] = evenData[index];
// evenData[index] = temp;
evenSum += data[index];
}
else
{
// int temp = data[index];
// data[index] = oddData[index];
// oddData[index] = temp;
oddSum += data[index];
}
}
System.out.println("Even Sum: " + evenSum);
System.out.println("Odd Sum: " + oddSum);
System.out.println("Total Sum: " + sum);
So, you don't need to create extra arrays for even and odd numbers.
And, also your 4 loops have now been condensed to just a single loop.
int temp = data[index];
data[index] = evenData[index];
evenData[index] = temp;
Looking at your above lines, evenDate is empty and in second line you are setting your data array to be empty. You are repeating the same mistake in oddDate line as well.
Why don't you use just try the following?
for(int index = 0; index < data.length; index++)
{
if (data[index] % 2 == 0) {
int temp = data[index];
evenData[index] = temp;
} else {
int temp = data[index];
oddData[index] = temp; }
}
}
for(int evenIndex = 0; evenIndex < evenData.length; evenIndex++)
{
//since length of all 3 data,even, odd arrays are the same
//you can put both sum operation in one for loop
evenSum = evenData[evenIndex] + evenSum;
oddSum = oddData[evenIndex] + oddSum;
sum = data[evenIndex] + sum;
}
System.out.print("Sum of even elements: " + evenSum);
//you have put evenSum for below odeUm printing in ur code
System.out.print("Sum of odd elements: " + oddSum);
System.out.print("Sum of all elements: " + sum);