What happens with the code after the recursion line ? [duplicate] - java

This question already has answers here:
Recursive Method Prints 4 Times
(4 answers)
Closed 5 years ago.
I want to ask exactly what happens with the code after the recursion line ?
Here is sample code :
public static void method(int index){
--index;
if (index < 0) {
return;
}
method( index);
System.out.println(index);
}
My question is why sout prints my number in reverse order when it is after the recursion line : 0 1 2 3 4
Thanks in advance.

Before each print you call method(number-1)
When reach -1 you start calling the recursion stack from 0 until your number index
The stack is piling and we keep popping the last one from stack:
0
1
...
number-1
number

Your application is single thread, so all instructions are executed one after one.
Once you call a method next line is called after method completes.
Your execution of method(4) is as it follows:
method(4)
method(3)
method(2)
method(1)
method(0)
method(-1)
- here, there is no more recursion call - method returns before calling method another time. Look, it returns, so we fall back to method(0) execution - print 0 is executed. Then we return and finish method(1):
print 0
print 1
print 2
print 3
print 4

Related

atomic integer counter printing in wrong order

I have defined the following instance variable:
private final AtomicInteger tradeCounter = new AtomicInteger(0);
I have a method called onTrade defined as below being called by 6 threads:
public void onTrade(Trade trade) {
System.out.println(tradeCounter.incrementAndGet());
}
Why is the output:
2
5
4
3
1
6
Instead of
1
2
3
4
5
6
?
I want to avoid using synchronization.
You can think of
tradeCounter.incrementAndGet();
And
System.out.println();
as two separate statements.
So here
System.out.println(tradeCounter.incrementAndGet());
there are basically two statements, and those statements together are not atomical.
Imagine such example with 2 threads :
Thread 1 invokes tradeCounter.incrementAndGet()
Thread 2 invokes tradeCounter.incrementAndGet()
Thread 2 prints value 2
Thread 1 prints value 1
It all depends in what order threads will invoke inctructions in your method.
I have a method called onTrade defined as below being called by 6
threads:
public void onTrade(Trade trade) {
System.out.println(tradeCounter.incrementAndGet());
}
Why is the output:
2 5 4 3 1 6
Instead of 1 2 3 4 5 6 ?
Why shouldn't that be the output? Or why not 3 1 4 6 5 2? Or any of the other permutations of 1 2 3 4 5 6?
Using an AtomicInteger and its incrementAndGet() method ensures that each each thread gets a different value, and that the six values obtained are sequential, without synchronization. But that has nothing to do with the order in which the resulting values are printed afterward.
If you want the results to be printed in the same order that they are obtained, then synchronization is the easiest way to go. In that case, using an AtomicInteger does not gain you anything over using a plain int (for this particular purpose):
int tradeCounter = 0;
synchronized public void onTrade(Trade trade) {
System.out.println(++tradeCounter);
}
Alternatively, don't worry about the order in which the output is printed. Consider: is the output order actually meaningful for any reason?
incrementAndGet() increments in the expected order : 1, 2, 3 etc...
But system.out doesn't invoke the println() in an atomic way along incrementAndGet(). So the random ordering is expected.
I want to avoid using synchronization.
You could not in this case.
System.out.println(...) and tradeCounter.incrementAndGet() are two separate operations and most likely when thread-i gets new value, some other threads can get value and print it before thread-i prints it. There is no way to avoid synchronization (direct or indirect) here.

Recursion - mystery1

Having a tough time with the below code, I have answered the first call correctly as the condition is immediately correct. However, the second call of 4 is causing me great confusion, I came to the answer 2, 1 however it is incorrect- I am clearly getting things mixed up. Can someone explain to me exactly why my answer is wrong and the correct breakdown of the process of Recursive tracing in this example. I do understand elements of recursion however I am having issues following the process of tracing.
public void mystery1(int n) {
if (n <= 1) {
System.out.print(n);
} else {
mystery1(n / 2);
System.out.print(", " + n);
}
}
mystery1(1);
mystery1(4);
mystery1(16);
Recursion is beautiful yet very powerful and when it comes to observe it, people get tricked.
Let me explain you how i learnt it when i was preparing for my GATE(Graduate Aptitude Test in Engineering).
Think of each Function call as 2 parts:
Printing
Calling with halving itself
Now all the operations will be stacked upon the older one until unless we are out of recursion and only Printing is left in the function cycle.
We will print out in stack format i.e FIFO
Example, if we have these elements in stack:
Top:
4
3
7
2
Bottom
It will print 4 3 7 2 .
Now taking your Question:
Lets break your Conditional statements in two halves, 1st will be if condition with Print 2nd will be else with its print.
Note: Only one part i.e 1st will print 1 and that too without commas (,).
I have attached the Image below kindly refer it, think as print statement as on stack, and the lowest print statement will be executed first as we will end out of function calls.
Now combining mystery1(1),mystery1(4),mystery1(16) the final output will be: 1
1
, 2
, 4
1
, 2
, 4
, 8
, 16
PS: If you are going to give interviews of Amazon , Google or any Reputed Product based company they will ask question with flavor of recursion and that too without using any compiler, they wanna test your concepts via programming.
When you call mystery1(4), it goes to the else part and calls mystery1(2) since n>1. The print statement will be executed only after mystery1(2) has finished executing.
The same thing happens for mystery1(2) and it calls mystery1(1). It waits for mystery(1) to finish execution.
When mystery1(1) is called, it prints "1".
Then, mystery1(2) will continue and print ",2".
Finally, mystery1(4) will continue and print ",4".
So your output will be 1,2,4
In your method:
public static void mystery1(int n) {
if (n <= 1) {
System.out.print(n);
} else {
mystery1(n / 2);
System.out.print(", " + n);
}
}
try to replace the position of System.out.print(", " + n); before mystery1(n / 2); call.
In the first case, when System.out after mystery1 call, you have result as 1, 2, 4, because, first you have to get result, then print it.
In the second case, when System.out before mystery1 call, you have result as , 4, 21, because, first you print the result, then calculate the next result in function.

for loops executed 3 times where it should be just once [duplicate]

This question already has answers here:
Why my method being called 3 times after System.in.read() in loop
(3 answers)
Closed 4 years ago.
I just started learning coding (Java) for days and I found this problem.
It is a very simple for loops program where the loops will stop executed after the user input an 'S' on the keyboard. It works fine, but if I put the wrong input the loops executed 3 times instead of just once.
class ForTest {
public static void main (String[]args)
throws java.io.IOException {
int i;
System.out.println("Press S to stop.");
for(i = 0; (char) System.in.read() != 'S'; i++)
System.out.println("Pass #" + i);
}
}
When I put the wrong input, the output should be:
Pass #0
But the actual output are:
Pass #0
Pass #1
Pass #2
Also if I put the wrong input more than one character, it always gives 2 extra output. Let's just say I put an input ABC (3 character). The output will be:
Pass #0
Pass #1
Pass #2
Pass #3
Pass #4
Is the problem are on the code? Can anyone explain why and share the solution?
Note: I tried to run the code on Command Prompt and Eclipse. Both have the same output.
TY,
I would assume its because of the carriage return and the line feed characters when you press enter after typing "ABC"

Can anyone explain how this code prints 1 to 10?

Can anyone explain how this code prints 1 to 10???
class demo
{
public static void main(String[] args)
{
display(10);
}
private static void display(int n)
{
if (n > 1)
{
display(n - 1);
}
System.out.println(n);
}
}
It's a recursive call to display method. Here the argument value passed to display method is stored in a stack. when the if condition fails then the value of n if poped from stack and printed by line "System.out.println(n)".
In other words, Every time display method called by passing a number, the number will be stored in a stack so that when code will come out of recursion, it will use that number from stack.
Doing the dry run you can see when the value 1 is passed to display method the if condition fails and the next line prints the value 1 then 2 will be printed which was in stack and so on it will print up to 10 which is the first value passed.
So the main method runs the display method and passes a value of 10. Then, the value is checked to see if it is greater than 1 (which it is). Next. the display method is called again with a value of n-1, which is 9 in this case. Lastly, 10 is printed out.
Now 9 goes through the same cycle. 9 is greater than 1 and display is called with a value of n-1, which is now 8. 9 is printed out and now 8 goes through the display method. This continues to happen until the value is 1 in which case 1 is not greater than 1 and 1 is printed out and the program exits.
This is called a recursive method if you would like to look into it more.

Recursion output

I was just introduced to recursion and I was given the following lines of code:
public class RecursionThree
{
public void run(int x )
{
if(x<5)
run(x+1);
out.println(x);
}
public static void main(String args[] )
{
RecursionThree test = new RecursionThree ();
test.run(1);
}
}
and the output is supposed to be: 5 4 3 2 1. I get why it would print 5 (because 5<5 would equal false and it would print x, which is 5). However, I do not understand why it prints 4 3 2 1 too. Thanks for your help
How recursion works is you break down to the base case and build up backwards. In your case. Your base case was x>=5, the point at which it would stop expanding the recursive tree, you can think of the base case as the end of the tree, or leaf. After that it goes back up completing things that were to be done after run was called. SO in your case, each time after calling one, it printed out x.
When x=1, it calls run(2), after run(2) is resolved, it would go to the next line. After run(2), the print out is 5 4 3 2 after that it would print out x coming back to the original call of run(1), which would be 1. This is really great for traversing trees etc and a lot of other problems.
To picture it, when you call run(1)
run(1)
1<5
run(2)
2<5
run(3)
3<5
run(4)
4<5
run(5)
print(5)
print(4)
print(3)
print(2)
print(1)
As you can see it goes to the base case, and back up.
To get familiar with recursion more, you can do problems like, finding the largest int in an array with the method head being public int findLargest(int [] array, int someNumber) where you would use someNumber to whatever you think you need. Or reversing a string using recursion and one parameter.
For your x=4 case, run(5) was called. After that completed running, control was returned to the callee function, where x is presently 4. So, it executes the line after the if which prints the 4.
The same logic follows for x = 3, 2, 1.

Categories

Resources