Selection Sort Method not Working? - java

Recently I have written a java program that executes selection sort on an array, however, it does not seem to return the correct output. What am I doing wrong?
Wanted output: [2.0, 3.7, 6.2, 7.4, 8.1, 8.5, 9.9, 15.7]
Actual output: [7.4, 2.0, 3.7, 6.2, 8.1, 8.5, 9.9, 15.7]
Code explanation: The method findMax finds the index of the largest object in the array, and the method process utilizes the method findMax to find the index of the largest number and swap it with the last, second-to-last, third-to-last, and so on term in order to put the array in order.
My code:
import java.util.Arrays;
import java.io.*;
public class Driver01
{
public static void main(String[] args)
{
//input
double[] myArray = {2.0, 3.7, 9.9, 8.1, 8.5, 7.4, 15.7, 6.2};
//sort the array
double[] sorted = process(myArray);
//output
System.out.println(Arrays.toString(sorted));
}
private static int findMax( int EndIndex, double[] enterArray) {
double max = 0;
int trueIndex = 0;
for( int x = 0; x < EndIndex; x++) {
if(enterArray[x] > max) {
max = enterArray[x];
trueIndex = x;
}
}
return trueIndex;
}
private static void swap(int swap1, int swap2, double[] enterArray) {
double temp = 0;
temp = enterArray[swap1];
enterArray[swap1] = enterArray[swap2];
enterArray[swap2] = temp;
}
private static double[] process(double[] enterArray) {
int range = enterArray.length -1;
for( int x = 0; x < enterArray.length; x++) {
int j = findMax(range, enterArray);
swap(j, range, enterArray);
range = range -1;
}
return enterArray;
}
}

When you call:
int j = findMax(range, enterArray);
in process(), range is defined as
int range = enterArray.length-1
So your findMax() function is not going through the entire array
You can fix this by changing your for loop in findMax() function to:
for (int x = 0; x < EndIndex+1; x++) {
...
}
There is probably a more elegant solution, but that is the problem in your code
EDIT:
A better solution would be to change your process() function to:
private static double[] process(double[] enterArray) {
int range = enterArray.length;
System.out.println("Array Length: " + enterArray.length);
for (int x = 0; x < enterArray.length; x++) {
int j = findMax(range, enterArray);
swap(j, range-1, enterArray);
range--;
}
return enterArray;
}
This way, findMax() is able to cycle through the full range of the array and swap is able to access the last element of the array. range is decremented since the max number is now the last element of the array. This is easier to understand from an outside perspective than my original answer.

Related

How to use create 2 Array with User input with Std.readAllInts()

This is how it should work, i Put in put for the 1 st array like: 2 3 1 2 3 4 5 6 then 2 and 3 are row and colum and the rest are the values. Problem is the 1st array work, but when i reach EOF ( ctrl+z) then there is out of bound exception. Which mean i cant input value for the 2nd Array like the 1st one. I know there is anotherway where that i can declare array size first then value. But how could i fix this f i still want to usr StdIn.readAllInts() ?
public class MatrixMult {
public static void main(String[] args){
System.out.println("First Matrix Config");
int[] einGabeMatrix1= StdIn.readAllInts();
int zeileM1 = einGabeMatrix1[0];
int spalteM1 = einGabeMatrix1[1];
int[][] ersteMatrix= new int [zeileM1][spalteM1];
int k=2;
int sum;
for(int i=0;i<zeileM1-1;i++){
for(int j=0;j<spalteM1-1;j++){
ersteMatrix[i][j]=einGabeMatrix1[k];
k++;
}
}
System.out.println("Second Matrix Config");
int[] einGabeMatrix2 = StdIn.readAllInts();
int zeileM2 = einGabeMatrix2[0];
int spalteM2 = einGabeMatrix2[1];
int h=2;
int[][] zweiteMatrix= new int [zeileM2][spalteM2];
for(int m=0;m<zeileM2-1;m++){
for(int n=0;n<spalteM2-1;n++){
zweiteMatrix[m][n]=einGabeMatrix2[h];
h++;
}
}
int[][] ergebnisMatrix= new int [zeileM1][spalteM2];
for (int t = 0; t < zeileM1; t++) {
for (int c = 0; c < spalteM2; c++) {
sum = 0;
for (int d = 0; d < spalteM1; d++) {
sum = sum + ersteMatrix[t][d] * zweiteMatrix[d][c];
}
ergebnisMatrix[t][c] = sum;
}
}
for(int i=0;i<zeileM1;i++){
for(int j=0;j<spalteM1;j++){
System.out.println(ergebnisMatrix[i][j]);
}
}
}
}
// This is StdIn.readAllInts(), standard method by java.
public static int[] readAllInts() {
String[] fields = readAllStrings();
int[] vals = new int[fields.length];
for (int i = 0; i < fields.length; i++)
vals[i] = Integer.parseInt(fields[i]);
return vals;
}
It looks like the issue is coming from the fact that StdIn.readAllInts() reads until the EOF. There will be no values left to read by the time your code gets to the second call.
I would suggest instead using the StdIn.readInt() call to read each integer one at a time and then you can use it within your loop to read the exact number of values your need.
Here is an example of how you could get the first 2 integers to find your matrix size:
int zeileM1 = StdIn.readInt();
int spalteM1 = StdIn.readInt();
You will also need to apply this method in your for loops to read the data into the matrix.

ArrayList giving problems in java. positive integers solution to x+y+z+w = 13

So i am creating a method that basically gives all possible positive integer solutions to the problem x+y+z+w = 13. Really I have designed a program that can get all possible positive integer solutions to any number using any number of variables. I have managed to obtain the solution using this method:
public class Choose {
public static ArrayList<int[]> values;
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] loops = new int[3];
int q = 0;
values = new ArrayList<int[]>();
int[] array = new int[4];
System.out.println(choose(12,3));
NestedLoops(3,10,0,loops,13,array, 0);
for(int i = 0; i < values.size(); i++){
printArray(values.get(i));
}
}
public static void NestedLoops(int n, int k, int j,
int[] loops, int q, int[] array, int g){
if(j==n){
for(int i = 0; i< n; i++){
q-=loops[i];
}
if(q>0){
for(int i = 0; i < n; i++){
array[i] = loops[i];
}
array[n] = q;
values.add(array);
}
return;
}
for(int count = 1; count <= k; count++){
loops[j] = count;
NestedLoops(n,k,j+1,loops, 13, array, g);
}
}
}
My problem is that when i go to print the ArrayList, all i get is the last value repeated again and again. When i try to just print out the values instead of storing them in the ArrayList it works totally fine. This makes me think that the problem is with the values.add(array); line but i don't know how to fix it or what i am doing wrong. Thanks for any help offered.
Try using:
values.add(array.clone());
Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant.

tukey's ninther for different shufflings of same data

While implementing improvements to quicksort partitioning,I tried to use Tukey's ninther to find the pivot (borrowing almost everything from sedgewick's implementation in QuickX.java)
My code below gives different results each time the array of integers is shuffled.
import java.util.Random;
public class TukeysNintherDemo{
public static int tukeysNinther(Comparable[] a,int lo,int hi){
int N = hi - lo + 1;
int mid = lo + N/2;
int delta = N/8;
int m1 = median3a(a,lo,lo+delta,lo+2*delta);
int m2 = median3a(a,mid-delta,mid,mid+delta);
int m3 = median3a(a,hi-2*delta,hi-delta,hi);
int tn = median3a(a,m1,m2,m3);
return tn;
}
// return the index of the median element among a[i], a[j], and a[k]
private static int median3a(Comparable[] a, int i, int j, int k) {
return (less(a[i], a[j]) ?
(less(a[j], a[k]) ? j : less(a[i], a[k]) ? k : i) :
(less(a[k], a[j]) ? j : less(a[k], a[i]) ? k : i));
}
private static boolean less(Comparable x,Comparable y){
return x.compareTo(y) < 0;
}
public static void shuffle(Object[] a) {
Random random = new Random(System.currentTimeMillis());
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + random.nextInt(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
public static void show(Comparable[] a){
int N = a.length;
if(N > 20){
System.out.format("a[0]= %d\n", a[0]);
System.out.format("a[%d]= %d\n",N-1, a[N-1]);
}else{
for(int i=0;i<N;i++){
System.out.print(a[i]+",");
}
}
System.out.println();
}
public static void main(String[] args) {
Integer[] a = new Integer[]{17,15,14,13,19,12,11,16,18};
System.out.print("data= ");
show(a);
int tn = tukeysNinther(a,0,a.length-1);
System.out.println("ninther="+a[tn]);
}
}
Running this a cuople of times gives
data= 11,14,12,16,18,19,17,15,13,
ninther=15
data= 14,13,17,16,18,19,11,15,12,
ninther=14
data= 16,17,12,19,18,13,14,11,15,
ninther=16
Will tuckey's ninther give different values for different shufflings of the same dataset? when I tried to find the median of medians by hand ,I found that the above calculations in the code are correct.. which means that the same dataset yield different results unlike a median of the dataset.Is this the proper behaviour? Can someone with more knowledge in statistics comment?
Tukey's ninther examines 9 items and calculates the median using only those.
For different random shuffles, you may very well get a different Tukey's ninther, because different items may be examined. After all, you always examine the same array slots, but a different shuffle may have put different items in those slots.
The key here is that Tukey's ninther is not the median of the given array. It is an attempted appromixation of the median, made with very little effort: we only have to read 9 items and make 12 comparisons to get it. This is much faster than getting the actual median, and has a smaller chance of resulting in an undesirable pivot compared to the 'median of three'. Note that the chance still exists.
Does this answer you question?
On a side note, does anybody know if quicksort using Tukey's ninther still requires shuffling? I'm assuming yes, but I'm not certain.

Better minimum and maximum algorithm using an array in Java

I was trying to write a simple max and min method, as I wrote it I just cant help feeling it shouldn’t be this complicated….maybe Im wrong?
My maximum code works like this, excuse my poor pseudo code:
Fill an array with 10 random numbers.
Create a max variable initialised to 0, because 0 is the lowest max.
Compare each element against the max
If the element is greater then max, replace the value of max with the element in question
I don’t like the fact I have to initialise max to 0, I feel there might be a better way then this?
My min code works similar except I:
Compare my min is lower then the array element.
If the element is lower replace min.
What I really don’t like about this is I have to initialise my min to the maximum random number, in this case 50.
My questions are:
Is there a better way to do this?
Is there a more efficient way to write this code?
import java.util.Random;
public class Main {
public static void main(String[] args) {
//Declare min and max
int max=0;
int min;
//Array of 10 spaces
int[] ar=new int[10];
//fill an array with random numbers between 0 and 50
for(int i=0;i<10;i++)
{
ar[i]=new Random().nextInt(50);
}
//Test max algorithm
//loop trough elements in array
for(int i=0;i<10;i++)
{
//max is set to 0, there should always be a maximum of 0
//If there isnt 0 will be the maximum
//If element is greater then max
//replace max with that element
if(ar[i]>max)
{
max=ar[i];
}
}
System.out.println("The max is "+ max);
//Test min
//Initialising min to maximum Random number possible?
min=50;
for(int i=0;i<10;i++)
{
if(ar[i]<min){
min=ar[i];
}
}
System.out.println("The min is "+min);
}
}
You can always grab the first element of the array (i.e. numbers[0]) as the initial value and start the loop from the second element.
int[] numbers = new int[10];
int max, min;
...
min = max = numbers[0];
for(int i = 1; i < numbers.length; ++i) {
min = Math.min(min, numbers[i]);
max = Math.max(max, numbers[i]);
}
Ok, while others were already posting answers, I have taken the time to edit your code into something I think would be more usable.
Make static methods. Those can be reused.
Use an ellipsis (...) because you then can either call the methods on array arguments like in your code, but also with a variable number of arguments as min(5,3,8,4,1).
Initialize with the smallest/biggest possible number the data type provides
To check that your code works, you have to print out the items in the array first, since when you don't know what's in it, there's no way to tell the result is correct.
Base your code on the existing methods in the standard library because these are known to be thoroughly tested and work efficiently (I know, min/max looks like a too trivial example).
I wouldn't bother too much about performance unless you really can show there is a performance problem in your code. Priority should be more like 1st correctness, 2nd readability/maintainability, 3rd performance.
Most of this has been already mentioned by others, but anyway, here's the code:
import java.util.Random;
public class MinMax {
public static int min(int... args) {
int m = Integer.MAX_VALUE;
for (int a : args) {
m = Math.min(m, a);
}
return m;
}
public static int max(int... args) {
int m = Integer.MIN_VALUE;
for (int a : args) {
m = Math.max(m, a);
}
return m;
}
public static void main(String[] args) {
// fill an array with random numbers between 0 and 50
int[] ar = new int[10];
for (int i = 0; i < 10; i++)
{
ar[i] = new Random().nextInt(50);
System.out.println(ar[i]);
}
int maxValue = max(ar);
int minValue = min(ar);
System.out.println("The max is " + maxValue);
System.out.println("The min is " + minValue);
}
}
Few tips:
Initialize min with first element and start from the second:
int min = ar[0];
for(int i=1;i<10;i++)
...or start from:
int min = Integer.MAX_VALUE;
this approach is better if you expect your array can be empty.
Use Math.min to avoid explicit condition (some may say it's slower though):
for(int i=0;i<10;i++)
{
min = Math.min(min, ar[i]);
}
Initialize max to 0 & min to 50 won't work when the numbers change. A more appropriate way is:
1. initialize them to the first element of the array.
2. Use length instead of a constant.
max = ar[0];
for(i=0;i<ar.length; i++)
{
if(ar[i]>max)
{
max=ar[i];
}
}
Same for min:
min = ar[0];
for(i=0;i<ar.length; i++)
{
if(ar[i]<min)
{
min=ar[i];
}
}
public static void main(String[] args) {
int[] myArray = {9, 7,9, -40, -10, 40};
//int[] myArray = {};
//int[] myArray = {4};
System.out.println("Difference between max and min = "
+ findDifference(myArray));
}
// Find difference between Max and Min values for a given array
public static int findDifference(int[] arr) {
if (arr.length == 0) {
// Log
System.out.println("Input Array is empty");
return Integer.MIN_VALUE;
}
int min = arr[0];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if (arr[i] < min)
min = arr[i];
else if (arr[i] > max)
max = arr[i];
// Just to check if logic works fine
System.out.println("Min=" + min + " Max=" + max);
}
return max - min;
}
import java.io.*;
public class MultiDimensionalArrayIO {
public static void main(String[] args)throws IOException {
BufferedReader c= new BufferedReader (new InputStreamReader (System.in) );
System.out.print ( "Enter Number Column : " );
int column = Integer.parseInt(c.readLine());
System.out.print ( "Enter Number Row : " );
int row = Integer.parseInt(c.readLine());
int array [][] = new int [column][row];
int max = array [0][0];
int min = array [0][0];
int sum= 0;
for ( int i=0 ; i < array.length; i++){
for (int j=0 ; j<array[i].length; j++){
System.out.print("Enter Array Values ["+i+"]["+j+"]: " );
array[i][j]= Integer.parseInt (c.readLine());
min = Math.min(min , array[i][j]);
max = Math.max(max , array[i][j]);
sum += array[i][j];
}
}
System.out.println("The Min Number :"+ min);
System.out.println("The Max Number :"+ max+ " total is "+ sum);
}
}
Depending on whether you'd want the max and min-functions in the same method you also have to consider the return type.
So far most suggestions have kept the two separate, meaning it's fine to return an int. However, if you put the max and min-functions into a findLargestDifference-method you'd have to return a long seeing as the largest difference between any given numbers in the int array can be the size of 2 ints. You'd also getting rid of having to loop over the int array twice.
Furthermore I recommend writing unit tests for corner and edge cases instead of printing in a main-method. It helps test your logic early on when implementing it and thus often makes the code cleaner.
See example code below.
public class LargestDifference {
public static long find(int[] numbers) {
if (numbers == null || numbers.length == 0) {
throw new IllegalArgumentException("Input cannot be null or empty.");
}else {
long currentMax = numbers[0];
long currentMin = numbers[0];
for (int i=0; i < numbers.length; i++) {
if (currentMin > numbers[i]) {
currentMin = numbers[i];
}else if (currentMax < numbers[i]) {
currentMax = numbers[i];
}
}
return currentMax - currentMin;
}
}

How do you find the sum of all the numbers in an array in Java?

I'm having a problem finding the sum of all of the integers in an array in Java. I cannot find any useful method in the Math class for this.
In java-8 you can use streams:
int[] a = {10,20,30,40,50};
int sum = IntStream.of(a).sum();
System.out.println("The sum is " + sum);
Output:
The sum is 150.
It's in the package java.util.stream
import java.util.stream.*;
If you're using Java 8, the Arrays class provides a stream(int[] array) method which returns a sequential IntStream with the specified int array. It has also been overloaded for double and long arrays.
int [] arr = {1,2,3,4};
int sum = Arrays.stream(arr).sum(); //prints 10
It also provides a method
stream(int[] array, int startInclusive, int endExclusive) which permits you to take a specified range of the array (which can be useful) :
int sum = Arrays.stream(new int []{1,2,3,4}, 0, 2).sum(); //prints 3
Finally, it can take an array of type T. So you can per example have a String which contains numbers as an input and if you want to sum them just do :
int sum = Arrays.stream("1 2 3 4".split("\\s+")).mapToInt(Integer::parseInt).sum();
This is one of those simple things that doesn't (AFAIK) exist in the standard Java API. It's easy enough to write your own.
Other answers are perfectly fine, but here's one with some for-each syntactic sugar.
int someArray[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int sum = 0;
for (int i : someArray)
sum += i;
Also, an example of array summation is even shown in the Java 7 Language Specification. The example is from Section 10.4 - Array Access.
class Gauss {
public static void main(String[] args) {
int[] ia = new int[101];
for (int i = 0; i < ia.length; i++) ia[i] = i;
int sum = 0;
for (int e : ia) sum += e;
System.out.println(sum);
}
}
You can't. Other languages have some methods for this like array_sum() in PHP, but Java doesn't.
Just..
int[] numbers = {1,2,3,4};
int sum = 0;
for( int i : numbers) {
sum += i;
}
System.out.println(sum);
In Apache Math : There is StatUtils.sum(double[] arr)
The only point I would add to previous solutions is that I would use a long to accumulate the total to avoid any overflow of value.
int[] someArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, Integer.MAX_VALUE};
long sum = 0;
for (int i : someArray)
sum += i;
int sum = 0;
for (int i = 0; i < yourArray.length; i++)
{
sum = sum + yourArray[i];
}
In Java 8
Code:
int[] array = new int[]{1,2,3,4,5};
int sum = IntStream.of(array).reduce( 0,(a, b) -> a + b);
System.out.println("The summation of array is " + sum);
System.out.println("Another way to find summation :" + IntStream.of(array).sum());
Output:
The summation of array is 15
Another way to find summation :15
Explanation:
In Java 8, you can use reduction concept to do your addition.
Read all about Reduction
A bit surprised to see None of the above answers considers it can be multiple times faster using a thread pool. Here, parallel uses a fork-join thread pool and automatically break the stream in multiple parts and run them parallel and then merge. If you just remember the following line of code you can use it many places.
So the award for the fastest short and sweet code goes to -
int[] nums = {1,2,3};
int sum = Arrays.stream(nums).parallel().reduce(0, (a,b)-> a+b);
Lets say you want to do sum of squares , then Arrays.stream(nums).parallel().map(x->x*x).reduce(0, (a,b)-> a+b). Idea is you can still perform reduce , without map .
int sum = 0;
for (int i = 0; i < myArray.length; i++)
sum += myArray[i];
}
IMHO a sum function would seem a good fit to extend the Arrays class where fill, sort, search, copy, & equals live. There are a lot of handy methods hiding in the javadocs so it is a fair question when porting Fortran to java to ask before rolling our own helper method. Search through the huge javadoc index for "sum", "add" and any other keyword you might think of. You might suspect certainly someone has already done this for primitive types int, float, double, Integer, Float, Double? No matter how simple, it is always good to check. Keep the code as simple as possible and don't reinvent the wheel.
It depends. How many numbers are you adding? Testing many of the above suggestions:
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Locale;
public class Main {
public static final NumberFormat FORMAT = NumberFormat.getInstance(Locale.US);
public static long sumParallel(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array).parallel().reduce(0,(a,b)-> a + b);
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumStream(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array).reduce(0,(a,b)-> a + b);
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumLoop(int[] array) {
final long start = System.nanoTime();
int sum = 0;
for (int v: array) {
sum += v;
}
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumArray(int[] array) {
final long start = System.nanoTime();
int sum = Arrays.stream(array) .sum();
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static long sumStat(int[] array) {
final long start = System.nanoTime();
int sum = 0;
final long end = System.nanoTime();
System.out.println(sum);
return end - start;
}
public static void test(int[] nums) {
System.out.println("------");
System.out.println(FORMAT.format(nums.length) + " numbers");
long p = sumParallel(nums);
System.out.println("parallel " + FORMAT.format(p));
long s = sumStream(nums);
System.out.println("stream " + FORMAT.format(s));
long ar = sumArray(nums);
System.out.println("arrays " + FORMAT.format(ar));
long lp = sumLoop(nums);
System.out.println("loop " + FORMAT.format(lp));
}
public static void testNumbers(int howmany) {
int[] nums = new int[howmany];
for (int i =0; i < nums.length;i++) {
nums[i] = (i + 1)%100;
}
test(nums);
}
public static void main(String[] args) {
testNumbers(3);
testNumbers(300);
testNumbers(3000);
testNumbers(30000);
testNumbers(300000);
testNumbers(3000000);
testNumbers(30000000);
testNumbers(300000000);
}
}
I found, using an 8 core, 16 G Ubuntu18 machine, the loop was fastest for smaller values and the parallel for larger. But of course it would depend on the hardware you're running:
------
3 numbers
6
parallel 4,575,234
6
stream 209,849
6
arrays 251,173
6
loop 576
------
300 numbers
14850
parallel 671,428
14850
stream 73,469
14850
arrays 71,207
14850
loop 4,958
------
3,000 numbers
148500
parallel 393,112
148500
stream 306,240
148500
arrays 335,795
148500
loop 47,804
------
30,000 numbers
1485000
parallel 794,223
1485000
stream 1,046,927
1485000
arrays 366,400
1485000
loop 459,456
------
300,000 numbers
14850000
parallel 4,715,590
14850000
stream 1,369,509
14850000
arrays 1,296,287
14850000
loop 1,327,592
------
3,000,000 numbers
148500000
parallel 3,996,803
148500000
stream 13,426,933
148500000
arrays 13,228,364
148500000
loop 1,137,424
------
30,000,000 numbers
1485000000
parallel 32,894,414
1485000000
stream 131,924,691
1485000000
arrays 131,689,921
1485000000
loop 9,607,527
------
300,000,000 numbers
1965098112
parallel 338,552,816
1965098112
stream 1,318,649,742
1965098112
arrays 1,308,043,340
1965098112
loop 98,986,436
I like this method personally. My code style is a little weird.
public static int sumOf(int... integers) {
int total = 0;
for (int i = 0; i < integers.length; total += integers[i++]);
return total;
}
Pretty easy to use in code:
int[] numbers = { 1, 2, 3, 4, 5 };
sumOf(1);
sumOf(1, 2, 3);
sumOf(numbers);
I use this:
public static long sum(int[] i_arr)
{
long sum;
int i;
for(sum= 0, i= i_arr.length - 1; 0 <= i; sum+= i_arr[i--]);
return sum;
}
You have to roll your own.
You start with a total of 0. Then you consider for every integer in the array, add it to a total. Then when you're out of integers, you have the sum.
If there were no integers, then the total is 0.
There are two things to learn from this exercise :
You need to iterate through the elements of the array somehow - you can do this with a for loop or a while loop.
You need to store the result of the summation in an accumulator. For this, you need to create a variable.
int accumulator = 0;
for(int i = 0; i < myArray.length; i++) {
accumulator += myArray[i];
}
You can make your code look better like this:
public void someMethod(){
List<Integer> numbers = new ArrayList<Integer>();
numbers.addAll(db.findNumbers());
...
System.out.println("Result is " + sumOfNumbers(numbers));
}
private int sumOfNumbers(List<Integer> numbers){
int sum = 0;
for (Integer i : numbers){
sum += i;
}
return sum;
}
Use below logic:
static int sum()
{
int sum = 0; // initialize sum
int i;
// Iterate through all elements summing them up
for (i = 0; i < arr.length; i++)
sum += arr[i];
return sum;
}
I have the right solution for your problem if you specifically have an array of type double, then this method can be used to calculate the sum of its elements. also, it using math class
import org.apache.commons.math3.stat.StatUtils;
public class ArraySum {
public static void main(String[] args) {
double[] array = { 10, 4, 17, 33, -2, 14 };
int sum = (int)StatUtils.sum(array);
System.out.println("Sum of array elements is: " + sum);
}
}
There is a sum() method in underscore-java library.
Code example:
import com.github.underscore.U;
public class Main {
public static void main(String[] args) {
int sum = U.sum(java.util.Arrays.asList(1, 2, 3, 4));
System.out.println(sum);
// -> 10
}
}
There is no 'method in a math class' for such thing. Its not like its a square root function or something like that.
You just need to have a variable for the sum and loop through the array adding each value you find to the sum.
class Addition {
public static void main() {
int arr[]={5,10,15,20,25,30}; //Declaration and Initialization of an Array
int sum=0; //To find the sum of array elements
for(int i:arr) {
sum += i;
}
System.out.println("The sum is :"+sum);//To display the sum
}
}
We may use user defined function. At first initialize sum variable equal to zero. Then traverse the array and add element with sum . Then update the sum variable.
Code Snippet :
import java.util.*;
import java.lang.*;
import java.io.*;
class Sum
{
public static int sum(int arr[])
{
int sum=0;
for(int i=0; i<arr.length; i++)
{
sum += arr[i];
}
return sum;
}
public static void main (String[] args)
{
int arr[] = {1, 2, 3, 4, 5};
int total = sum(arr);
System.out.printf("%d", total);
}
}
/**
* Sum of all elements from 1 to 1000
*/
final int sum = Stream.iterate(1, n -> n + 1).limit(1000).mapToInt(el -> el).sum();
Most of the answers here are using inbuilt functions-
Here is my answer if you want to know the whole logic behind this ques:
import java.util.*;
public class SumOfArray {
public static void main(String[] args){
Scanner inp = new Scanner(System.in);
int n = inp.nextInt();
int[] arr = new int[n];
for(int i = 0; i < n; i++){
arr[i] = inp.nextInt();
}
System.out.println("The sum of the array is :" + sum(arr));
}
static int sum(int[] arr){
int sum = 0;
for (int a = 0; a < arr.length; a++){
sum = sum + arr[a];
}
return sum;
}
}
public class Num1
{
public static void main ()
{
//Declaration and Initialization
int a[]={10,20,30,40,50}
//To find the sum of array elements
int sum=0;
for(int i=0;i<a.length;i++)
{
sum=sum+i;
}
//To display the sum
System.out.println("The sum is :"+sum);
}
}
public class AddDemo {
public static void main(String[] args) {
ArrayList <Integer>A = new ArrayList<Integer>();
Scanner S = new Scanner(System.in);
System.out.println("Enter the Numbers: ");
for(int i=0; i<5; i++){
A.add(S.nextInt());
}
System.out.println("You have entered: "+A);
int Sum = 0;
for(int i=0; i<A.size(); i++){
Sum = Sum + A.get(i);
}
System.out.println("The Sum of Entered List is: "+Sum);
}
}
As of Java 8 The use of lambda expressions have become available.
See this:
int[] nums = /** Your Array **/;
Compact:
int sum = 0;
Arrays.asList(nums).stream().forEach(each -> {
sum += each;
});
Prefer:
int sum = 0;
ArrayList<Integer> list = new ArrayList<Integer>();
for (int each : nums) { //refer back to original array
list.add(each); //there are faster operations…
}
list.stream().forEach(each -> {
sum += each;
});
Return or print sum.

Categories