Can anyone explain how does the following recursion work? - java

I have some trouble understanding the following recursive code:
public class recursive {
public static void main(String[] args){
helper(0) ;
}
public static void helper(int i){
int a=3;
if(i==a){
System.out.println("yes:"+i);
return;
}else{
for(;i<a;i++){
System.out.println("no:"+i);
helper(i+1);
System.out.println("end:"+i);
}
}
}
}
The Output is as follows:
no:0
no:1
no:2
yes:3
end:2 //why this is 2?
end:1 //why this is 1?
no:2
yes:3
end:2
end:0
no:1
no:2
yes:3
end:2
end:1
no:2
yes:3
end:2
I do not understand why the first end is 2. Can anyone explain how does the recursion work in this simple program?

try
public static void helper(int i){
int a=3;
if(i==a){
System.out.println("yes:"+i);
return;
}else{
System.out.println("no:"+i);
helper(i+1);
}
}
one idea of recursion is to do away with loops

Each call to helper has its own local value of i.
So when i==2, and you call helper(i+1), the next call to helper has i==3, but when it returns, it goes back to the previous helper invocation, for which i==2.

Related

Why is my method not returning anything?

Why is my method not returning anything?
class Test{
static int count = 0;
public static void main(String args[]){
String s = "------+ # ----+------";
countDoors(s);
}
public static int countDoors(String s){
char sigN= '+';
for(int i=0;i<s.length();i++)
if(s.charAt(i)==sigN)
count++;
return count;
}
}
I'm sure kinda a noobish question, but I really wanna understand why it isn't working
In main() method, you call countDoors(s);, it returns count value, but you do nothing with it.
If you want to just print this value to console, then change countDoors(s); to System.out.println(countDoors(s));
If you want to save the result of calling countDoors(s) to the variable to make a use of it later, there is an example how you can achieve it:
int savedValue = countDoors(s);

Recursion - why use return statement

I am learning recursion and below is one example that I am tracing through to better understand it
public static void main(String []args) {
new TestRecursion().strRecur("abc");
}
public void strRecur(String s) {
if(s.length() < 6) {
System.out.println(s);
strRecur(s+"*");
}
}
Below is what I have understood so far.
- In the first call to strRecur("abc"), the method gets added to execution stack. It prints "abc" before pausing due to a recursive call with parameter "abc*".
The second call with "abc*", pushes method strRecur(abc*) to the stack and prints "abc*" to console.
The third call with "abc**", pushes method strRecur(abc**) to the stack and prints "abc**" to console.
The fourth call with "abc***", pushes method strRecur(abc***) to the stack. Since the base condition is met, the method completes (without printing anything) and pops out of the stack.
The third call with "abc**" is completed and popped out. Since there is no pending code to execute nothing happens.
The second call with "abc*" is completed and popped out. Since there is no pending code to execute nothing happens.
The initial call with "abc" is completed and popped out. Since there is no pending code to execute nothing happens.
Prints following to the console -
abc
abc*
abc**
I think I understand what is happening here. Now, I want to try a slight variation of this code. Instead of callingstrRecur(s+"*"), I would like to do return strRecur(s+"*")
public class TestRecursion {
public static void main(String []args) {
new TestRecursion().strRecur("abc");
}
public String strRecur(String s) {
if(s.length() < 6) {
System.out.println(s);
return strRecur(s+"*");
}
return "Outside If";
}
}
My expectation was that, once strRecur(abc***) pops out, it's output (abc***) would be returned to the next strRecur() on the stack, so I would see abc**** printed in the console. Same for other recursive calls as well.
However, the output in this case is exactly the same as when there is no return statement. My understanding (which of course is not correct) stems from the recursive factorial implementation, where we do something like
return n * fact(n-1);
Here fact(n-1) is resolved with the returned value of n, once the previous method on the stack completes. Why doesn't return behave in the same way in this example?
The output of both methods is produced by the println statements within the recursive method, which is why it is identical in both methods.
The value returned by the second method is not printed anywhere, which is why you don't see it displayed.
If you would print the result of the second method, you will see it is "Outside If", since that's the output of the last recursive call, which is then returned by all the other method calls.
If you want the output to be abc***, you should
return s;
instead of
return "Outside If";
The full code would be:
public static void main(String[] args) {
System.out.println(new TestRecursion().strRecur("abc"));
}
public String strRecur(String s) {
if(s.length() < 6) {
return strRecur(s+"*");
}
return s;
}
Here is how to make it return the value instead of printing it:
public static void main(String[] args) {
String result = StrRecur("abc");
System.out.print(result);
}
public static String StrRecur(String s) {
if(s.length() < 6) {
return s + "\n" + StrRecur(s+"*");
}
return "";
}
This does the same, but the side effect happens only in main.

java - Stack and queue confusion

What is the difference between these two ways of dealing with stacks and queues? What are the both called?
First way:
import java.util.Arrays;
public class StackMethods {
private int top;
int size;
int[] stack ;
public StackMethods(int arraySize){
size=arraySize;
stack= new int[size];
top=-1;
}
public void push(int value){
if(top==size-1){
System.out.println("Stack is full, can't push a value");
}
else{
top=top+1;
stack[top]=value;
}
}
public void pop(){
if(!isEmpty())
top=top-1;
else{
System.out.println("Can't pop...stack is empty");
}
}
public boolean isEmpty(){
return top==-1;
}
public void display(){
for(int i=0;i<=top;i++){
System.out.print(stack[i]+ " ");
}
System.out.println();
}
}
Second way:
public class StackReviseDemo {
public static void main(String[] args) {
StackMethods newStack = new StackMethods(5);
newStack.push(10);
newStack.push(1);
newStack.push(50);
newStack.push(20);
newStack.push(90);
newStack.display();
newStack.pop();
newStack.pop();
newStack.pop();
newStack.pop();
newStack.display();
}
}
Also are they correct? trying to learn these well, but explanations across the internet are vague about these..
I'm not 100% sure what you mean with two ways.
Looking at your first code snippet, we can see that you are declaring the class StackMethods. In the second one you are instantiating an object of the class StackMethods.
So all you do in the main-method of your second code snippet is to create an object which is calling the methods push(), pop() and display() you declared in the class above. You didn't actually implement two datastructures, but just a basic stack.
The good news is, over all you have grasped the concepts of stacks, since your implementation of the class 'StackMethods' is correct overall.
In regards to what the difference between a Queue and a Stack is, this question might help you:
In case this didn't answer your question and I simply misunderstood it, please just comment and let me know so I can try to help you out a little better.

Return statement not working when calling another method

I have recently started experimenting with the return statement, and I have a small doubt relating to it- When I have a method which calls another method, will the return statement of that method which I am calling be displayed?
Let be give an example to make it clearer-
/** Program to test return statment */
public class Test
{
public static void main(int a)
{
EvenOrOdd(a);
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display(As in that window does not pop up with the result.)
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
If I were to simply remove the main method(or even make the second method public and run that directly), my return statement is displayed however if I attempt to call the method and run the program my return statement isn't displayed.
So is this just a problem I am facing or is it a general rule in Java that the return statement doesn't work when you call another method(which has a return statement)?
If it is the latter, then I apologise, I was not aware of this.
Thanks...
***UPDATE***
It seems that nobody has understood what I exactly mean. I will give another example-
Please run this program-:
/** Program to test Return statment;simple program to return sum of two digits */
public class Return_Test
{
public static int main(int a,int b)
{
return a+b;//What I am lloking for is that box in which this is displayed.
}
}
A return statement only returns the value ,does not Display it
If you don’t catch the return value , how can it be displayed? add something like this and try
,
public class Test
{
public static void main(int a)
{
boolean temp=EvenOrOdd(a);
if(temp)
System.out.println("Output is True");
else
System.out.println("Output False(not even )");
//Or you can directly call the method as' System.out.println(EvenOrOdd));'
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
And Please try learning some good Naming Conventions , Classes are Named like this ,
FirstSecond,TestException(Each Word Starts with a Capital Letter) etc , methods start with a small letter , isPrime() , isEven(),
What a lot of other responders don't know is that when you run a method in BlueJ, it executes the method, and if the the return value of the method is non-void, it is shown in a popup dialog by invoking toString. That's what the questioner means by the value being displayed.
The answer to the user's original question is that by surrounding the method with a void return, it "hides" the result. So this code:
public void callMe1(int a)
{
EvenOrOdd(a);
}
will not display the return. But if you adjust the return type and actually return the value of the inner call:
public int callMe2(int a)
{
return EvenOrOdd(a);
}
Then BlueJ will display the returned value. The display aspect is down to BlueJ, but the rules for whether or not the value gets returned are the same as in Java; void means no return.
Within the body of the method, you use the return statement to return the value. It will not print anything on its own.
Changes done - System.out.println(EvenOrOdd(5));
public class Test {
public static void main(String[] args) {
System.out.println(EvenOrOdd(5));
}
private static boolean EvenOrOdd(int a) {// I can declare as public and run directly but then what is the point in
// calling the method?
if (a % 2 == 0) {
System.out.println("The output is true.");// Displays
return true;// Does not display
} else {
System.out.println("The output is false.");// Displays
return false;// Does not display
}
}
}
Output
The output is false.
false
You never actually display the return result from the method...
The name of the method is consuming EvenOrOdd returning true or false is ambigious, may isEven would be better...
You could try something like...
System.out.println(a + " is even = " + EvenOrOdd(a));
You should also avoid using multiple return statements within a single method, it can quickly become confusing as to how the method actually works, in your case, you can reduce the over complexity at the same time, for example...
private static boolean isEven(int a)
{
boolean isEven = false;
if(a%2==0)
{
System.out.println("The output is true.");//Displays
isEven = true;//Does not display
}
return isEven;
}
first change your main signature from main(int a) to main(String [] args) otherwise you will get following runtime exception :
Error: Main method not found in class yourpackagename.Test, please define the main method as:
public static void main(String[] args)
well you didn't print the value return from function :
in your main do this:
System.out.println(EvenOrOdd(5));

What classifies as a recursive function in Java

does this count as a recursive function...if no, then what is the reason. Which changes would classify it as such...thanks
public class Recursion {
public static void recursionFunc(int beginning_value){
if (beginning_value != 0){
System.out.println(beginning_value);
recursionFunc(beginning_value - 1);
}
}
public static void main(String[] args){
recursionFunc(10);
}
}
A function that calls itself, directly or indirectly, is called recursive. Your function calls itself, so it is definitely recursive.
Here is an example of recursive functions that calls themselves indirectly:
static void funcA(int x) {
if (x <= 0) return;
if (x % 2 == 0) {
funcB(x-1);
} else {
funcC(x-1);
}
}
static void funcB(int x) {
funcA(x-1);
}
static void funcC(int x) {
funcA(x-2);
}
Your method is a recursive method. A method is considered to be recursive when it calls itself again. All recursion methods should some sort of exit built into it, otherwise the method will yield an Stackoverflow error.
Here is a recursive method that does not have a exit built into it:
static void callAgain() {
callAgain();
}
Here's more details on recursive methods:
http://danzig.jct.ac.il/java_class/recursion.html

Categories

Resources