# Sum of Array

• 01-03-2009, 09:43 AM
Mika
Sum of Array
Can you help me regarding recursion in java?
This is Mr. Nicholas program but he did not use recursion in java in this program.Can you give the program using recursion in java.This is about summing the elements within an array.

import javax.swing.*;
public class ArraySum
{
public static void main(String []args)
{
try
{
int x = Integer.parseInt(JOptionPane.showInputDialog("Ente r a number:"));
if( x > 0)
int y = x;
int z = 0;
// allocate an array for integers
int array[] = new int[x];
//
while(y > 0)
{
z += --x;
array[--y] = z;
}
int index = 0;
final int limit = array.length;
while(++index < limit)
{
System.out.println(array[index]);
}
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

your help is very well appreciated.Thank You
• 01-03-2009, 09:45 AM
Eranga
What you have tried so far?
• 01-03-2009, 10:13 AM
Mika
I have her my progarm but i dont know how to implement it coorectly. can you help me. it has 5 errors, her the statement

C:\ArraySum.java:8: illegal start of expression
int z[]=array([x]);
^
C:\ArraySum.java:8: ')' expected
int z[]=array([x]);
^
C:\ArraySum.java:14: invalid method declaration; return type required
public static array(int a, int n) {
^
C:\ArraySum.java:17: ')' expected
return array((a,n-1)+a[n-1]);
^
C:\ArraySum.java:17: ')' expected
return array((a,n-1)+a[n-1]);
^
• 01-03-2009, 10:27 AM
Mika
sum of array
Here's another program i make but it has 1 error in my main method,what should i do?what variable should i declare to receive the result from the recursive function.Can you help me?pls..

import javax.swing.*;
public class ArraySum {
public static void main(String []args)throws Exception {

for(int y=0;y<=10;y++) {
int x=Integer.parseInt(JOptionPane.showInputDialog("En ter a number:"));
int z=result();
System.out.println(z);
}
}

int sum( int arr[], int size )
{
int result;
if ( size == 0 ) // base case
result = 0;
else
{
// recursive call
int smallResult = sum( arr, size - 1 );

// use solution of recursive call to solve this problem
result = smallResult + arr[ size - 1 ];
}
return result;
}
}
• 01-03-2009, 10:38 AM
Eranga
Quote:

Originally Posted by Mika
I have her my progarm but i dont know how to implement it coorectly. can you help me. it has 5 errors, her the statement

C:\ArraySum.java:8: illegal start of expression
int z[]=array([x]);
^
C:\ArraySum.java:8: ')' expected
int z[]=array([x]);
^
C:\ArraySum.java:14: invalid method declaration; return type required
public static array(int a, int n) {
^
C:\ArraySum.java:17: ')' expected
return array((a,n-1)+a[n-1]);
^
C:\ArraySum.java:17: ')' expected
return array((a,n-1)+a[n-1]);
^

Here the initialization of an array is completely wrong.