Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Recursive Method to compute cumulative sums in an array

Posted on 2012-09-06
5
Medium Priority
?
1,824 Views
Last Modified: 2012-09-08
Hi guys!

I'm trying to write this java code where I need to write a recursive method that will compute cumulative sums in an array This is the output I should have

Numbers in array: 2,3,1,5,6,2,7

Output should be: 2,5,6,11,17,19,26

I kind used the Fibonacci method but I'm not sure if I'm doing it right! Here is the code..



public class cumulativearray
{
    public static void main (String[] args)
    {

     int[] array= {2,3,1,5,6,2,7};
               
        System.out.println("The result is:");
        System.out.println(sumofarray(array, 0));
        

    }


    public static int sumofarray(int[] array, int indicator)
    {
     
                  
                  if(indicator == array.length)
                        return 0;
                  else
                  
                    return sumofarray(array, indicator - 1) + sumofarray(array, indicator - 2);
    }
      
}
0
Comment
Question by:hugonieto
  • 2
  • 2
5 Comments
 
LVL 21

Accepted Solution

by:
Amitkumar P earned 1332 total points
ID: 38372904
please check the below code....

public class RecursiveSum {

	public static void main(String[] strArgs) {
		
		int[] values = {2,3,1,5,6,2,7};
		
		System.out.println();
		System.out.print("Main Values :: ");
		printValues(values);
		
		System.out.println();
		System.out.print("Cumulative Sum :: ");
		printCumulativeSum(values, 0, 0);
		
	}
	
	private static void printValues(int[] values) {
		if (values!=null && values.length>0) {
			
			for (int i : values) {
				System.out.print(i + " ");	
			}
		}
	}
	
	private static void printCumulativeSum(int[] values, int sum, int index) {
		if (values!=null && values.length>0) {
			
			sum = sum + values[index++];
			System.out.print(sum + " ");
			if (index < values.length ) {
				printCumulativeSum(values, sum, index);		
			} else {
				return;
			}
		}
	}
}

Open in new window

0
 

Author Comment

by:hugonieto
ID: 38373460
Thanks for the response amit_n_panchal!

If Understand well, the printValues method is printing just the values of the array...... and the printCumulativeSum method is doing the cumulative operation and printing the values already calculating the previous numbers. A few questions..... the line if (values!=null && values.length>0) { is the base case to stop the recursion right? and this line  sum = sum + values[index++]; is doing the addition of the previous numbers? meaning the cumulative sum .... I'm sorry, it is just that I'm trying to understand what the code is doing. is there a way to write the method printCumulativeSum  more simple? I kind came up
(with help) with a recursive method to sum the numbers in an array (below). It took me a lot of time trying to figure out how to do it.... I have some knowledge about java....  the problem comes when someone gives me a problem or ask me to write a program... I don't know how to write it or what method to use..... like the sample you just did..... I never thought that it could've been done like that... How do you do it? I mean able to understand what method to use when solving a java problem..


public static int sumofarray(int[] array, int indicator)
{
  if(indicator ==array.length)
 return 0;
else
return array[indicator] + sumofarray(array, indicator + 1);
}
0
 
LVL 86

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 668 total points
ID: 38373666
Here's a similar approach that instead stores the sums in an output array:
public class cumulativearray {

    public static void main (String[] args) 
    { 

    	int[] data = {2,3,1,5,6,2,7};
    	int[] sums = CumulativeSums(data);
    	
        System.out.println("data:");
        PrintArray(data);
        
        System.out.println("sums:");
        PrintArray(sums);
    } 

    public static int[] CumulativeSums(int[] source)
    {
    	int[] result = null;
    	if (source != null)
		{
			result = new int[source.length];
			CumulativeSums(source, 0, result);
		}
    	return result;
    }
    
	private static void CumulativeSums(int[] source, int index, int[] destination) 
    {
		if (source != null & destination != null)
		{
	    	if (index >= 0 & index < source.length & source.length == destination.length) 
	    	{
	    		if (index == 0)
	    		{
	    			destination[0] = source[0]; 
	    		}
	    		else
	    		{
	    			destination[index] = source [index] + destination[index - 1]; 
	    		}
	    		CumulativeSums(source, ++index, destination); 
	    	}
		}
    }

    public static void PrintArray(int[] source)
    {
    	if (source != null)
    	{
    		for(int i = 0; i < source.length; i++)
    		{
    			if (i > 0)
    			{
    				System.out.print(", ");    			
    			}
    			System.out.print(source[i]);
    		}
    		System.out.println("");
    	}
    }
    
}

Open in new window

0
 
LVL 21

Assisted Solution

by:Amitkumar P
Amitkumar P earned 1332 total points
ID: 38376964
Below code snippet is used to stop recursion..

if (index < values.length ) {
	printCumulativeSum(values, sum, index);		
} else {
	return;
}

Open in new window


Thru the experience, you can learn which method to use when. It happens at initial level, don't worry. Keep practicing on Java and try to write the code for various problems.

You can start with http://projecteuler.net/ that provides various kind of problems/algorithms.
0
 

Author Comment

by:hugonieto
ID: 38379607
Thanks  amit_n_panchal!
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article explores the design of a cache system that can improve the performance of a web site or web application.  The assumption is that the web site has many more “read” operations than “write” operations (this is commonly the ca…
We take a look at the fast-evolving changes in Search Engine Optimization rules and algorithms by Google.
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month13 days, 13 hours left to enroll

581 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question