I have been trying to figure out why the output is 321 and not 123. I have tried multiple times and looking out lecture slides but I still can't get the solution to this question.
public static void main(String[] args) {
printNumber(1);
}
public static void printNumber(int n) {
if(n!=4) {
printNumber(n + 1);
System.out.print(n);
}
}
Each call to printNumber calls printNumber(n+1) first, and then prints something out. So printNumber(n+1) has already finished before printNumber(n) prints its number out.
main():
printNumber(1):
printNumber(2):
printNumber(3):
printNumber(4) // does nothing
print(n) // "3"
// printNumber(3) completes, returning control to printNumber(2)
print(n) // "2"
// printNumber(2) completes, returning control to printNumber(1)
print(n) // "1"
// printNumber(1) completes, returning control to main()
// main() completes
The variable n is either 1 2 or 3.
What are you printing first, n or n + 1? You are printing n + 1 first, then n. So the numbers must come out in reverse order.
The reason for this result that you have placed the recursion call statement printNumber(n + 1)
before print statement System.out.print(n) so it will keep recursivly calling it until it reach 4 after that it will print numbers from last call n+1 to n as in our example from 3 to 1
try this :
public static void printNumber(int n) {
if(n!=4) {
System.out.print(n);
printNumber(n + 1);
}
}
you will find the output: 123
The reason for that is at each recursion call it will print the number n then it will call it another time for n+1 until it reach 4.
Related
Im supposed to write a method divideByTwo that takes an integer as a parameter and returns the number divided by 2. and i need to try to solve the problem with a single program statement in the method. I don't know how to fix the problem, i've used modulo, while loop, changed the return value but still don't know what i am doing wrong. Any kind of help appreciated!
this is what i've done so far:
public static int divideByTwo(int a){
int i = 0;
while(i < 1){
System.out.print(a/2);
i++;
}
return a;
}
expected output
The reason why you are getting 51 when you're entering 10 in the example is because it prints 10/2 = 5 and then it returns i which is 1. Then you are printing the method with parameter 10 which prints 5 in the method and then 1 as the return value. If you just want to divide the number by two, then all you need to write in the method is return a/2; and then just print the method divideByTwo(a);.
You are out-thinking yourself. The method has a simple purpose - divide the value provided by 2 and return that result.
remove the print statement - there is nothing to print
remove the loop and loop variable - there is nothing to loop over
That leaves you with...
public static int divideByTwo(int a) {
return a;
}
... but we don't want a - we want a divided by 2. You did the division in your print statement so do that division in the return statement and you are done.
public static int divideByTwo(int a) {
return a/2;
}
The answer was in you all along!
This question already has an answer here:
Recursive function : print statement before/after function call
(1 answer)
Closed 11 months ago.
I can't seem to figure out why this recursion program prints the values the way it does. I thought it would print [9]9 first but intead it does it backwards from [0]0. Can anyone explain why this happens?
class RecTest {
int values[];
RecTest (int i){
values = new int[i];
}
void printArray(int i) {
if(i==0) return;
else printArray(i-1);
System.out.println("[" + (i-1) + "]" + values[i-1]);
}
}
public class Recursion2 {
public static void main(String[] args) {
RecTest ob = new RecTest (10);
int i;
for(i=0; i<10; i++) ob.values[i] = i;
ob.printArray(10);
}
}
The printArray method works by calling itself decreasing the integer i. The System.out.println statement is executed after calling the function with i-1. For example, given an input of 10:
printArray(10) is exectued -> printArray(10-1) is called
printArray(9) is executed -> printArray(9-1) is called
[...]
printArray(0) is executed -> return. The program goes back to the previous istance of printArray, the one where i = 1
We are here in the code: the line printArray(1-1) has just been executed. The next line is System.out.println("[" + (1-1) + "]" + values[1-1]) -> [0]0 is printed (right now i = 1). Now the program goes back to the previous instance where i = 2
[...]
I think you can figure out the rest :)
See if this helps.
static void printVal(int i) {
if (i > 0) {
System.out.printf("Calling printVal(%d) again%n", i-1);
printVal(i-1);
}
System.out.println("Returning from print - call stack has " + i);
}
printVal(10);
prints
Calling printVal(9) again
Calling printVal(8) again
Calling printVal(7) again
Calling printVal(6) again
Calling printVal(5) again
Calling printVal(4) again
Calling printVal(3) again
Calling printVal(2) again
Calling printVal(1) again
Calling printVal(0) again
Returning from print - call stack has 0
Returning from print - call stack has 1
Returning from print - call stack has 2
Returning from print - call stack has 3
Returning from print - call stack has 4
Returning from print - call stack has 5
Returning from print - call stack has 6
Returning from print - call stack has 7
Returning from print - call stack has 8
Returning from print - call stack has 9
Returning from print - call stack has 10
Each subsequent call to printVal puts the value-1 on the call stack. When they are all finally returned, they return in the reverse order.
I'm trying to solve the problem of "count ways to reach the nth step in a staircase" with recursion. When given a number of stairs to climb, I have to calculate the number of ways to climb taking either 1 or 2 steps at a time. For example, if there are 4 stairs, we would return 5 since we would have:
* 1 1 1 1
* 1 1 2
* 1 2 1
* 2 1 1
* 2 2
My code is currently throwing a stack overflow exception:
public static int countWaysToClimb(int stairs) {
return countWaysToClimbHelper(stairs, 0, 0);
}
public static int countWaysToClimbHelper(int sumNeeded, int currentSum, int possibleCombos) {
// base - we will reach this base multiple times
if (sumNeeded == currentSum) {
possibleCombos++;
// if we already found a combo, we need to reset the sum
countWaysToClimbHelper(sumNeeded,0,possibleCombos);
}
else if (currentSum > sumNeeded) {
return 0;
}
// recurse - add 1 and then add 2
countWaysToClimbHelper(sumNeeded,currentSum+1,possibleCombos);
countWaysToClimbHelper(sumNeeded,currentSum+2,possibleCombos);
return possibleCombos;
}
Thank you!
There are some issues in your code:
Base case (condition that terminates the recursion) is incorrect. Every branch of recursive calls spawn new branches when it hits the condition if (sumNeeded == currentSum) is meat instead of returning the number of combinations. You created an infinite recursion that inevitably leads to a StackOverflowError. You have to place a return statement inside the curly braces after the first if in your code. And comment out the first recursive call (with 0 sum passed as an argument) you'll face the second problem: for any input, your code will yield 0.
Results returned by recursive calls of your method countWaysToClimbHelper() are omitted. Variable possibleCombos isn't affected by these calls. Each method call allocates its own copy of this variable possibleCombos on the stack (a memory aria where JVM stores data for each method call), and their values are not related anyhow.
you actually don't need to pass the number of combinations as a parameter, instead you have to return it.
Before moving further, let me recap the basics of recursion.
Every recursive method should contain two parts:
base case - that represents a simple edge-case for which the outcome is known in advance. For this problem, there are two edge-cases:
sumNeeded == currentSum - the return value is 1, i.e. one combination was found;
sumNeeded > currentSum - the return value is 0.
recursive case - a part of a solution where recursive calls a made and when the main logic resides. In your recursive case you need to accumulate the value of the number of combination, which will be the sum of values returned be two branches of execution: take 1 step or 2 steps.
So the fixed code might look like that:
public static int countWaysToClimb(int stairs) {
return countWaysToClimbHelper(stairs, 0);
}
public static int countWaysToClimbHelper(int sumNeeded, int currentSum) {
// base - we will reach this base multiple times
if (sumNeeded == currentSum) {
return 1;
} else if (currentSum > sumNeeded) {
return 0;
}
// recurse - add 1 and then add 2
int possibleCombos = 0;
possibleCombos += countWaysToClimbHelper(sumNeeded,currentSum + 1);
possibleCombos += countWaysToClimbHelper(sumNeeded,currentSum + 2);
return possibleCombos;
}
Note:
This code could be enhanced further. The whole logic can be implemented inside the countWaysToClimb() without using a helper-method. For that, instead of tracking the currentSum you need to subtract the number of steps from the sumNeeded when the method is called recursively.
public class Test{
public static int sum(int num){
if (num <= 1){
return num;
}
return 2 + sum(num -1);
}
public static void main(String []args){
System.out.print(sum(7));
}
}
I'm trying to understand recursion? Why is it when I run this code the answer is 13?
Follow it by hand on paper. The first thing that happens is sum(7). That call checks for num <= 1, which is false. So, in order to do the next line, it has to call sum(6). The original call is pushed on the stack, and we start handling sum(6). That call also falls through the if, and calls sum(5).
Eventually we are nested 7 levels deep:
sum(7)
sum(6)
sum(5)
sum(4)
sum(3)
sum(2)
sum(1)
Now, in the sum(1) call, num is <= 1, so we return 1. They key is, where do we return? We return out one level, to the call for sum(2). Its call to sum(1) returned 1. We add 2 to that and return 3.
Now, we're in the sum(3) call. It got 3, so it returns 5.
Now, we're in the sum(4) call. It got 5, so it returns 7.
And so on. Eventually, we get to the outer sum(7) call. Its call to sum(6) returned 11; it adds 2 and returns 13.
The main function gets 13.
sum(1) is 1.
sum(2) is 2 + sum(1), so it's 3.
sum(3) is 2 + sum(2), so it's 5.
sum(4) is 2 + sum(3), so it's 7.
sum(5) is 2 + sum(4), so it's 9.
sum(6) is 2 + sum(5), so it's 11.
sum(7) is 2 + sum(6), so it's 13.
I'm new to java programming, and our teacher taught us the concept of recursion and I found it to be a bit complicated. All I understood that it works like a loop(like the factorial of 4) but I still don't quite get it why it works like that. Can I get a detailed explanation on this topic? Here is the piece of code and a picture my teacher used to explain.
package javaapplication1;
public class JavaApplication1 {
static int factorial(int n){
int t;
if(n == 0){
return 1;
} else {
t = factorial(n - 1);
return n * t;
}
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
In the following image, the blue color represents stack winding, and the green is stack unwinding, and again I don't know what stack winding and unwinding is.
http://i.stack.imgur.com/pjqJy.png
A recursive function is a function that calls itself until it reaches a return statement, that stops it from recalling itself. Take your example, the Factorial function.
Factorial is a mathematical function that returns the number multiplied by itself - 1 multiplied by itself - 2, ... multiplied by 1, example: factorial of 5 = 5! = 5x4x3x2x1 = 120.
it is also equal to itself multiplied by the factorial of itself -1, which is: 5! = 5x4!
Take into consideration that 0! = 1.
to represent this in a Java code, you need a loop that multiplies the numbers starting from 1, and going till the number you are calculating its factorial.
Further more, explaining your code, let us calculate Factorial(5):
Factorial() returns an integer.
Initial Call from main(): 5 != 0, then skip the condition (n == 0); t
= Factorial(5-1) = Factorial(4);
Second call from Factorial(4): 4 != 0, then skip the condition (n ==
0); t = Factorial(4-1) = Factorial(3);
Third call from Factorial(3): 3 != 0, then skip the condition (n ==
0); t = Factorial(3-1) = Factorial(2);
Fourth call from Factorial(2): 2 != 0, then skip the condition (n ==
0); t = Factorial(2-1) = Factorial(1);
Fifth call from Factorial(1): 1 != 0, then skip the condition (n ==
0); t = Factorial(1-1) = Factorial(0);
Sixth call from Factorial(0): 0 == 0, then return value 1;
First return, 1, to Fifth call (Factorial(1)): return n*t = return 1*1
= return value 1;
Second return, 1, to Fourth call (Factorial(2)): return n*t = return
2*1 = return value 2;
Third return, 2, to third call (Factorial(3)): return n*t = return 3*2
= return value 6;
Second return, 6, to second call (Factorial(4)): return n*t = return
4*6 = return value 24;
Second return, 24, to First call (Factorial(5)): return n*t = return
5*24 = return value 120;
Second return, 120, to Initial call (from main()): print(120);
Hope this helps you understand recursion.
When a call is made to another method, a stack frame is created to hold the state of the current method and it is pushed onto the stack. This is regardless of a method calling itself or another method.
When the call returns, the stack frame is popped of the stack, the state of the method is restored and execution continues in the calling method.
Recursion is when a method (directly or indirectly) calls itself. The general form of a recursive method is:
If a parameter meets a terminating condition, return (usually a result)
Else adjust parameters for the next iteration and call self
The code your teacher wrote has some style issues. It would be clearer if written like this:
static int factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
Eradicating the unnecessary variable t and redundant else (there is no "else" when the "if" returns - there is merely continuation of execution)
I would write it like this, eliminating the if altogether:
static int factorial(int n) {
return n == 0 ? 1 : n * factorial(n - 1);
}
When one knows that a task can be broken into similar smaller tasks ,then we use recursion or calling the same method(until we met a certain condition).Recursion not only helps in execution of a problem without having to define or invoke another method,it also helps in visualizing a pattern by which the task is getting executed
Personally, I do not like the factorial problem. I find it hard to understand and I do not think it explains recursion in a clear way. So lets look at a different example. Lets say that we want to print numbers from 1-100. This is a very simple task with a for loop and a counter, but it can also be done with recursion. For example:
public static void main(String[] args) {
numbersAscending(1);
numbersDescending(1);
}
//Prints 1 2 3 ... 100
public void numbersAscending(int x){
System.out.println(x);
if(x < 100){
numbersAscending(x+1);
}
}
//Prints 100 99 98 ... 1
public void numbersDescending(int x){
if(x < 100){
numbersDescending(x+1);
}
System.out.println(x);
}
When a function is called, that call goes on top of the stack. Think of this like a stack of cards. Each one has a number on it (1-100). When a function calls itself, a new card gets added to the stack. When the function finishes, it is taken off of the stack.
So for the example above, every time numbersAscending is called, it prints out the current value for x before calling that function again. This results in the numbers being printed in order from 1-100. As soon as 100 is reached, it stops calling itself and pops each function off of the stack.
On the other hand, every time numbersDescending is called, it calls itself again before printing out the number. In this way, x doesn't start printing until it reaches 100. It then moves back down the stack, printing each number as it goes back to the main method.
/*This program in java will help you to understand all the basics of
recursion:
->how control flows in recursion
->how return is executed in the recursive functions
->how and when the statements after recursive function area executed.*/
public class Understanding_Rec{
public static int rec(int x)
{
if(x<5)
{
System.out.println("-->Smaller than 5");
rec(x+1);
System.out.println("<--After recursion inside x<5");
return x;
}
else if(x<7)
{
System.out.println("-->Smaller than 7");
rec(x+1);
System.out.println("<--After recursion inside x<7");
}
System.out.println("<--No Condition Statement");
return x;
}
public static void main(String[] args)
{
int x=1;
rec(x);
System.out.print(x+"Inside main");
}
}
I am not sure if it explains, but if you had a precalculus class then you should know that factorial can be defined in two waqys.
n!=1*2*...*n
of we define
1!=1
and
n!=n*(n-1)!
Try to see yourself that those definitions are equivalent. Pick let us say, 5!
according to second definition
5!=5*4!
but 4!=4*3! so 5!=5*4*3!
but 3!=3*2! so 5!=5*4*3*2!
and so on. Keep doing it until you hit 1!. But 1!=1 so you stop.
Recursion in programming is the same thing.
TomW