I want to ask how to add the values and find average of values in an array. I have tried searching multiple times, but I could find something that explains how to do all that in simple code that a new programmer such as myself could understand. If someone could tell me how to do it and explain the codes used, that will be great. Thanks in advance :>
I leave the normal answers for others to do. For java people,Here we go!
public static void main(String[] args) {
int myarr[]={1,2,3,4,4,5,6,5,7,8,4};
IntSummaryStatistics statisticalData=Arrays.stream(myarr).summaryStatistics();
System.out.println("Average is " + statisticalData.getAverage());
System.out.println("Sum is " + statisticalData.getSum());
}
Other data like count,minimum element,maximum element can also be obtained from the IntSummaryStatistics object
public static void main(String args[]) {
Scanner s = new Scanner(System.in); //Define Scanner class object which will aid in taking user input from standard input stream.
int a[] = new int[10]; //Define an array
int i,sum = 0;
for(i = 0; i < 10; i++) {
a[i] = s.nextInt(); //Take the arrays elements as input from the user
}
for(i = 0; i < 10; i++) { //Iterate over the array using for loop. Array starts at index 0 and goes till index array_size - 1
sum = sum + a[i]; //add the current value in variable sum with the element at ith position in array. Store the result in sum itself.
}
double avg = (double) sum / 10; //Compute the average using the formula for average and store the result in a variable of type double (to retain numbers after decimal point). The RHS of the result is type casted to double to avoid precision errors
System.out.print(sum + " " + avg); //print the result
}
At first you have to take an array of numbers. Iterate all the numbers in the array and add the numbers to a variable. Thus after iteration you will get the sum of the numbers. Now divide the sum by count of numbers (which means the size of array). Thus you will get the average.
int[] numbers = {10, 20, 15, 56, 22};
double average;
int sum = 0;
for (int number : numbers) {
sum += number;
}
average = sum / (1.0 * numbers.length);
System.out.println("Average = " + average);
You can also iterate in this way:
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
void sumAndAverage(int a[]){
if(a!=null&&a.length>0{
int sum=0;
//traverse array and add it to sum variable
for(int i=0;i<a.length;i++){
sum=sum+a[i];
}
double avg=(1.0*sum)/a.length;
System.out.println("sum= "+sum);
System.out.println("average= "+avg);
}
}
Related
We have to pass the array through a method that takes the highest, lowest, and average then have them print.
I'm having issues with getting the lowest value assigned to minNum.
Thank you!
public static void averageMaxMinMethod(double[] arrayOfDoubles){
double maxNum = 0;
double minNum = 0;
for(int i = 0; i < arrayOfDoubles.length; i++){
if(arrayOfDoubles[i] > maxNum)
maxNum = arrayOfDoubles[i];
if(arrayOfDoubles[i] < minNum)// <=== My poor attempt of getting the lowest value
minNum = arrayOfDoubles[i];
}
System.out.println("Highest given double is: " + maxNum);
System.out.println("Lowest given double is: " + minNum);
}
public static void main(String[] args) {
//1-3: Set up Scanner object to collect user's input on the size of array.
Scanner keyboard = new Scanner(System.in);
System.out.println("How many double numerical entries do you have?");
//4: Declare an array of size sizeOfArray
int sizeOfArray = keyboard.nextInt();
//Initialize array
double[] arrayOfDoubles;
arrayOfDoubles = new double[sizeOfArray];
for(int i = 0; i < sizeOfArray; i++){
//5: Use the Random number Class and walk over the array
Random randomNum = new Random();
arrayOfDoubles[i] = randomNum.nextDouble(0.0 , 100.0);
}
//6: Invoke SumMethod
sumMethod(arrayOfDoubles);
averageMaxMinMethod(arrayOfDoubles);
}
double maxNum = 0;
double minNum = 0;
This only works if the maximum number is at least zero, and the minimum value is at most zero - otherwise, these values are not updated.
Instead, use the first element in the array, which is at least as large as the minimum, and at least as small as the maximum.
double maxNum = arrayOfDoubles[0];
double minNum = arrayOfDoubles[0];
Of course, you then don't need to compare these on the first loop iteration, so you can start the loop index at 1:
for(int i = 1; i < arrayOfDoubles.length; i++){
Others have pointed out the mistake you made in your current implementation, however you also forgot to calculate the average. You don't actually have to write code to do that, Java includes DoubleSummaryStatistics which can give you the max, the min, and the average. Like,
public static void averageMaxMinMethod(double[] arrayOfDoubles) {
DoubleSummaryStatistics dss = DoubleStream.of(arrayOfDoubles).summaryStatistics();
System.out.println("Highest given double is: " + dss.getMax());
System.out.println("Lowest given double is: " + dss.getMin());
System.out.println("Average is: " + dss.getAverage());
}
I am having trouble printing the values of an array declared with ArrayList.
I am using the enchanced for to print its values but what if i want to sum them.
import java.util.ArrayList;
import java.util.Scanner;
public class Program
{
public static void main(String[] args){
int sum = 0;
ArrayList<Integer> numbers = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
int x = input.nextInt();
while (x != -1){
numbers.add(x);//xonoyme ta stoixeia ston numbers
x = input.nextInt();
}
for (int y: numbers){
sum = sum + numbers;
System.out.print(y + " ");
}
System.out.print("to athroisma einai: " + sum);
}
}
the error is in the command
sum = sum + numbers;
Here:
sum = sum + numbers;
numbers is the list of numbers you are iterating on.
You probably meant:
sum = sum + y;
sum is a primitive int variable. The + operator only allows you to add other primitive numerical values here. You can't add a List<Integer> to an int value.
Alternatively, you can use Java 8 streams here:
numbers.stream().mapToInt(Integer::intValue).sum();
sums up all values in your list, too.
The program begins by asking the user to give a value assigned to variable n, the user will then be prompted to submit long digits n amounts of times. The digits will then be stored into the initialized array (ar). The function I am trying to create aVeryBigSum is to loop through the numbers in the array, incrementing sum=0 by the numbers in the array to provide the sum (Java).
For some reason however, the program works unless I use two consecutive numbers with greater than 9 digits.
For example:
aVeryBigSum(2,[111111111,111111111]) has n of 2 and two 9 digit numbers in the array
Output:
22222222
aVeryBigSum(2,[1111111111,1111111111]) has n of 2 and two 10 digit numbers in the array
Output:
-2072745074
Any idea what the issue might be? I've provided the program below:
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Main {
static long aVeryBigSum(int n, long[] ar) {
int sum = 0;
for (int i = 0; i < n; i++){
System.out.println(sum);
System.out.println(ar[i]);
sum += ar[i];
System.out.println(" ");
}
return sum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
long[] ar = new long[n];
for(int ar_i = 0; ar_i < n; ar_i++){
ar[ar_i] = in.nextLong();
}
long result = aVeryBigSum(n, ar);
System.out.println(result);
}
}
Your problem is in the line
int sum = 0;
It should read
long sum = 0;
You are triggering integer overflow when the sum of integers exceeds 32 bits.
Yes, agree with Mad Physicist. You have to use long sum = 0. But to be the completely correct, you have possibility to have sum greater than Long.MAX_VALUE. You could use e.g. BigDecimal:
static BigDecimal aVeryBigSum(int n, long[] ar) {
BigDecimal sum = BigDecimal.ZERO;
for (int i = 0; i < n; i++) {
System.out.println(sum);
System.out.println(ar[i]);
sum = sum.add(new BigDecimal(ar[i]));
System.out.println(" ");
}
return sum;
}
Write a full Java program that does the following:
Creates an array of 100 double.
Reads in an unknown number of doubles from a file named values.txt .
There will be at least 2 distinct values, and no more than 100 distinct values in the file. The values will be in unsorted order. Values will be no smaller than 0, and no larger than 99.
Outputs the most frequently occurring value in the file.
Outputs the least frequently occurring value in the file. The value must occur at least once in order to be output.
Outputs the average of all array values.
You must create and use separate methods for each of the items #2-5.
This is what I have so far. I cannot for the life of me figure out how to get this right:
import java.util.*;
import java.io.*;
public class arrayProgram2 {
static Scanner console = new Scanner(System.in);
static final int ARRAY_SIZE = 100;
static int numOfElements = 0;
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new FileReader("values.txt"));
double[] Arr1 = new double[ARRAY_SIZE];
while (inFile.hasNext()) {
Arr1[numOfElements] = inFile.nextDouble();
numOfElements++;
}
System.out.println("There are " + numOfElements + " values.");
System.out.printf("The average of the values is %.2f%n", avgArray(Arr1));
System.out.println("The sum is " + sumArray(Arr1));
inFile.close();
} //end main
//Method to calculate the sum
public static double sumArray(double[] list) {
double sum = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
return sum;
}
//Method to calculate the average
public static double avgArray(double[] list) {
double sum = 0;
double average = 0;
for (int index = 0; index < numOfElements; index++) {
sum = sum + list[index];
}
average = sum / numOfElements;
return average;
}
} //end program
Notice I am required to make an array of double even though it is not necessary.
If all values are int than you should use int array instead of double. As all values in range 0-99. So, you can increase input value frequency. Look at below logic:
int[] freqArr= new int[100];
while (inFile.hasNext()){
int value = inFile.nextInt();
freqArr[value]++; // count the frequency of selected value.
}
Now calculate the maximum frequency from freqArr
int maxFreq=0;
for(int freq : freqArr){
if(maxFreq < freq){
maxFreq = freq;
}
}
Note: If double array is mandatory than you can also use double array like:
double[] freqArr= new double[100];
while (inFile.hasNext()){
freqArr[(int)inFile.nextDouble()]++;
}
It's possible to find a most-occurring value without sorting like this:
static int countOccurrences(double[] list, double targetValue) {
int count = 0;
for (int i = 0; i < list.length; i++) {
if (list[i] == targetValue)
count++;
}
}
static double getMostFrequentValue(double[] list) {
int mostFrequentCount = 0;
double mostFrequentValue = 0;
for (int i = 0; i < list.length; i++) {
double value = list[i];
int count = countOccurrences(list, value);
if (count > mostFrequentCount) {
mostFrequentCount = count;
mostFrequentValue = value;
}
}
return mostFrequentValue;
}
Pham Thung is right : -
You read in integer inFile.nextInt(), why do you need to use double array to store them? – Pham Thung
You can achieve your first functionality in n time if its integer array.
you question says,
Values will be no smaller than 0, and no larger than 99.
So,
1. Make an array of size 100.(Counter[])
2. Iterate through values of your current array and add count to Counter array.
eg:
if double array contains
2 3 2 5 0 0 0
Our counter array will be like
location : 0 1 2 3 4 5 6 ...........100
values : 3 0 1 1 0 1 0 ..............
and so on.
You can use below algorithm for this
Sort the array (you only need to read unsorted array, but you can sort the array once read from the file)
Make double var : num, mostCommon, count = 0, currentCount = 1
Assign Arr1[0] to num
for i from 1 to length of Arr1
i. if(Arr1[i] == num)
a. Increment currentCount
ii. else
a. if(count > currentCount)
A. Assign currentCount to count
B. Assign num to mostCommon
C. Assign Arr1[i] to num
D. Assign 1 to currentCount
At the end of this loop, you will have most common number in mostCommon var and it's number of occurrence in count.
Note : I don't know how to format the algo
The method I'm building should print all values above the average values in the method.
I have built the method to calculate the average and then print only the values above that amount.
However it prints the values that are positive.
int total = 0;
for (int i = 0; i < intList.length; i++)
{
total += intList[i];
{
if (intList[i] > intList[total])
{
System.out.println(intList[i] + "\t");
}
}
}
return total;
How do I make it so instead of printing all positives it prints only the values in the array above the average value in the array?
You need two different loops. One to add all the numbers together to get the total. Then you need to get the average from that total. Then loop again to check and print
public static void main(String[] args) {
int[] values = new int[] { 1, 5, 2, 6, 3, 7, 4, 8 };
double sum = 0;
for (int value : values)
sum += value;
double avg = sum / values.length;
System.out.printf("AVG = %.2f\n----------\n", avg);
for (int value : values) {
if (value > avg)
System.out.println(value);
}
}
Output:
AVG = 4.50
----------
5
6
7
8
You have to loop 2 times, one for calculating average and then when you get total calculated you have to change if comparision. intList[i] > intList[total] to intList[i] > total
Example :
public static void main(String args[]){
int[] intList = {1,2,3,4,5,6,7,8,9,10};
int total = 0;
// first loop calculate
for (int i : intList){
total += i;
}
double average = total / (double)intList.length;//take care array can't be empty.
System.out.println("average :"+ average);
//then show
for(int i : intList){
if (i > average){
System.out.println(i + "\t");
}
}
}
The answers above nailed it, your second loop isn't comparing it to the average, rather the total. You need one loop first to get the average of the array, and then a second one to test the array against the average.
for (int i = 0;i < array.count; i++){
total = total + array[i]
}
average = total / array.count
for (int i = 0;i < array.count; i++){
if (array[i]>total){
print
}
}
Theres some pseudocode/ish to get you going.