Would really really love if someone could explain to me how this code I wrote is not even close to what I thought it would produce. I wrote the code trying to prove that int n was going to be n = 4 and so In my head and on paper I thought my results in step by step would be as followed:
- 4 * 4 + (3) = 19
- 3 * 3 + (2) = 11
- 2 * 2 + (1) = 5
- 1 * 1 + (0) = 2
return 0
Can someone tell me why it is not that? and walk me through the recursive steps?
public static void main(String[] args) {
Scanner kbd = new Scanner(System.in);
int n;
System.out.println("Enter a number: ");
n = kbd.nextInt();
System.out.println("recursive value "+intValue(n));
}
public static int intValue(int n)
{
int total;
int x;
if(n == 0)
return 0;
else
total = n * n + intValue(n-1);
System.out.println("Recursive total: "+total);
return total;
}
Aucun commentaire:
Enregistrer un commentaire