Results 1 to 7 of 7
Thread: Recursionsum..pls help??
- 02-18-2009, 01:45 AM #1
Member
- Join Date
- Dec 2008
- Location
- Davao Oriental
- Posts
- 29
- Rep Power
- 0
Recursionsum..pls help??
import javax.swing.*;
import java.util.Arrays;
public class Recursionsum {
public static void main(String[] args)throws Exception {
int []val=new int[20];
int i=Integer.parseInt(JOptionPane.showInputDialog("En ter a number:"));
int sum = addArray(val, 0,0);
System.out.println(sum);
}
public static int addArray(int[] a, int index, int sum) {
if(index == a.length-1) {
return sum + a[a.length-1];
} else {
return addArray(a, index+1, sum+a[index]);
}
}
}
I have my problem with this code because the output of this is wrong. Actually the task of this code, is to ask the user a number around 20 numbers. But then, the problem is when the user enter for example:
(2 3 4 2 1)5 numbers the output is zero that actually very wrong.
i want this code to add the all values enter by the user. so the(2 3 4 2 1)total of this is 12 and it will display the result.
Thank you.
- 02-18-2009, 02:00 AM #2
Senior Member
- Join Date
- Sep 2008
- Posts
- 564
- Rep Power
- 5
all your program does is ask for user input then go about doing practically nothing:
executes asJava Code:int sum = addArray(val, 0,0);
which basically returns 0 after a few recursive callsJava Code:public static int addArray(int[] a = val, int index = 0, int sum = 0) { return addArray(val, 0+1, 0+0); }
- 02-18-2009, 02:06 AM #3
Member
- Join Date
- Dec 2008
- Location
- Davao Oriental
- Posts
- 29
- Rep Power
- 0
What should i do?Can you give me the correct code of this.pls..i need this code now because it will be pass to our instructor. thank you very much.
-
so let me see if I'm getting this straight: you're in effect asking him to do your work for you, to cheat? Did I miss something here? Are you nuts?Can you give me the correct code of this.pls..i need this code now because it will be pass to our instructor
- 02-18-2009, 02:06 PM #5
Member
- Join Date
- Dec 2008
- Location
- Davao Oriental
- Posts
- 29
- Rep Power
- 0
Im sorry...
- 02-18-2009, 02:08 PM #6
Member
- Join Date
- Dec 2008
- Location
- Davao Oriental
- Posts
- 29
- Rep Power
- 0
Thank you for the help..
- 02-18-2009, 04:18 PM #7
lol.. Did you sort it out then?
I would suggest creating afew small programs that use for loops and arrays, once you understand how they both work, then use both of these together (ie, use a loop to populate an array).. once you have done this, you should understand where you are goin wrong :)
Good luck.They're 10 people in the world, those who speak binary, and those who dont.
^ Lame i know, but i can actually count in it nowadays! :eek:


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks