Explain the logic behind this program? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm a newbie to programming and today i came across this program. How did i get the output as 3? and the jargon used here is quite confusing.
class Demo
{
public static void main(String args[])
{
Demo d = new Demo(); // what does this really mean?
System.out.println(d.someMethod(124));
}
public int someMethod(int x)
{
if(x<=0)
return 0;
return 1 + someMethod(x/10);
}
}

below is the answer
1 + someMethod(12)
1 + 1+ someMethod(1)
1 + 1+ 1+ someMethod(0)
1 + 1+ 1+ 0
= 3

Reformatted class with comments:
class Demo {
// static method used to start a Java application
public static void main(String args[]) {
// create a new instance of the Demo class
Demo demo = new Demo();
// call instance method someMethod and print the return value
System.out.println(d.someMethod(124));
}
// someMethod is a recursive function, that is a function which
// calls itself until a stop condition is reached
public int someMethod(int x) {
// stop condition
if(x <= 0) {
return 0;
}
// recursive call
return 1 + someMethod(x/10);
}
}
What happens:
1 call someMethod(124/10)
2 call someMethod(12/10)
3 call someMethod(1/10)
4 return 0 (because 1/10 == 0 the stop condition is reached)
3 return 1 + 0
2 return 1 + 1 + 0
1 return 1 + 1 + 1 + 0
so the return value is 3.
Note that 1/10 == 0 because the result is floored (the remaining decimals are removed to make it an int).

Well first of all you create a Demo object with name d.Via this object you call a method named someMethod(x).
This method returns 0 if the input parameter is <=0 or in any other case 1 + someMethod(x/10).

Demo d = new Demo();
This line means that you are initialising a new object with name 'd' from a class called Demo (which is also your main class). If you don't understand what objects and classes are, read up on it elsewhere, because it is a very major topic in Java.
Personally this has helped me the most: https://docs.oracle.com/javase/tutorial/java/concepts/index.html
public int someMethod(int x) {
if(x<=0)
return 0;
return 1 + someMethod(x/10); }
This method is acting kind of like a loop. You are passing a value of 124 from:
System.out.println(d.someMethod(124));
here. 124 gets checked if it is smaller of equal to zero. It is not so it gets passed to:
return 1 + someMethod(x/10);
124/10 is 12.4, but as x is an int it will round it to 12. And the program carries on until x <= 0, which loops over 2 times like:
1 + someMethod(12)
1 + 1+ someMethod(1) // 12/10 is 1.2, but gets rounded to 1
1 + 1+ 1+ someMethod(0) // 1/10 is 0.1, but gets rounded to 0
And the program ends as the passed value is 0. So you get 3 as an output.

Demo d = new Demo() will call the Constructor of Demo Class. If there is not any constructor present in the class then JVM will create a default one. That's how the concept behind the object creation in Java.
and look the previous answer how the someMethod(args) will execute.

Related

Recursive solution to counting the number of ways you can go up a staircase

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.

I'm trying to understand recursion? Why is it when I run this code the answer is 13

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.

What is the incrementation process in recursion? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
As I was working through practice problems I came across this one where I am not sure how I got the wrong answer. I tried increasing the value of "i" by 1 and printing that value. This should print the output "5 6 7" but for some reason does not. I tried to google my answer but can't phrase the question correctly or get good results.
//assuming that the value of 'i' is 4
public static void test(int i) {
if (i < 8) {
test(i + 1);
System.out.print (i + “ “);
}
}
You call test before you print the value. If you originally invoke test with 5, the machine does this in pseudocode:
test(5)
test(5 + 1)
test(5 + 1 + 1)
test(5 + 1 + 1 + 1)
print 5 + 1 + 1 // 7
print 5 + 1 // 6
print 5
test is called; but before printing anything, it calls itself again with i + 1. This repeats until i is 8, and then it starts printing in the "most inside" function.
You should print first, and then call test again.
Since you are printing the value of i after the recursive call, the code will wait until the recursive function returns before printing the value. Which cause the number to be printed backward.
To prevent this, you might want to call the print statement before going into the recursive call.
public static void test(int i) {
if (i < 8) {
System.out.print (i + "");
test(i + 1);
}
}
You can test it with this anyfiddle

Recursion - Java Programming

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.

Define a sequence recursively in Java

Need help with this problem, I am very bad at recursion. I need to write a method that does this:
The input variable X is an integer between 1 and 50. The function should return as Y the X-th term of a sequence defined recursively by:
f(1) = 1
f(2) = 3
f(X) = 2*f(X-1) – 2*f(X-2) for X = 3,4,5,...
Your function code should use recursion (not a loop)
TBH I dont even know where to get started. Any help would be appreciated. Here is my current code:
package p1parta;
import java.util.Scanner;
public class RecursiveSeq
{
public static void main(String args[])
{
System.out.println("Please enter a number:");
Scanner input = new Scanner(System.in);
int x = input.nextInt();
System.out.println(sequence(x));
}
public static int sequence(int x)
{
if(x == 1){
return 1;
}
if (x == 2){
return 3;
}
return 2 * sequence(x - 1) - 2 * sequence(x - 2);
}
}
I tried to implement the solution shown but the output I get from the program do not match what I am calculating by hand. In fact just testing inputs 3,4,5,and 6 The only one that matches is 5
Your problem is a perfect use case for recursion. In general the recursive pattern is:
func(context)
if simple case
return simple answer
else
call func(simpler context)
and return combined results
Have a go at implementing using this pattern and come back if you have issues.

Categories