Question:
Help with a "running total sum" in Java problem?
2012-02-04 22:47:38 UTC
Is it possible to write a class whose purpose is to produce a progression, where each value is the sum of all the previous values?
Four answers:
modulo_function
2012-02-04 23:06:18 UTC
Sure!



Let's say you want the sum of 1/n starting at n=1:



double sum = 0;

for( int k=1;k<=100; k++ ) { // show first 100 sums:

...sum += 1.0/k;

...System.out.println( "sum through term "+k+" is "+sum );

}
?
2012-02-05 00:00:34 UTC
To expand on what others have mentioned. Yes, you can create a class to run the total sum. I believe your question is actually about Fibonacci sequence. In Fibonacci sequence each value is the sum of all previous. For example, 1 1 2 3 5 8 13...n.



Most likely you will need to use recursion to generate the expected result. Here is some code in java:



public int fibonacci(int n) {

if (n < 2) { //If n=1 or lower we return n

return n; //This is our base case.

}

else {

return fibonacci(n-1)+fibonacci(n-2);

//else, we use the code above

//example, if n = 3, then fibonacci(3-1) + fibonacci(3-1);

//(fibonacci(2) = fibonacci(2-1) + fibonacci(2-2)) + fibonacci(1)

//The above statement now moves into the base case

//1+0+1 = 2, remember these numbers are added because of the

//else statement.

}

}



We can conclude that when we are out of the base case that we now have to follow the recursion until it reaches the base case and bring all of the returned information back into the recursive statment.
?
2016-12-09 07:53:55 UTC
public type worker implements Comparablef8c8b93cb2e4f297e4b96d4b9c1e98a will resolve your undertaking ,and the needful casting will take place and not utilising a hitch... Kindly Take a observe of interfaces used...Its at situations slightly errors services,for all programmers...
green meklar
2012-02-04 23:05:07 UTC
Of course.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...