What is the output of following code - java

It should print only Number: -1
but it is printing Number: -1 0 1 2
Why it is printing this series?
I expect execution will go only once to System.out.println.
class MemoryJava {
public static void main(String[] args){
decreaseNumberbyOne(2);
}
public static void decreaseNumberbyOne(int num){
if(num >= 0){
decreaseNumberbyOne(num -1);
}
System.out.println("Number:"+num);
}
}

This is the sequence of events:
call (2)
call (1)
call (0)
call (-1)
do not call (-2) because <0
print -1
return
print 0
return
print 1
return
print 2
return
It is called recursion.
I would show code with an else to help you achieve the desired output, but for that look at the other answer by deadpool.

Try this will work, just mistake in your code, add System.out.println("Number:"+num); in else block
public static void main(String[] args){
decreaseNumberbyOne(2);
}
public static void decreaseNumberbyOne(int num){
if(num >= 0){
decreaseNumberbyOne(num -1);
} else{
System.out.println("Number:"+num);
}
}

Related

Fibonacci sequence will not print anything but the number that is inputted by the user

Here is my main method, I am trying to call the Fibonacci sequence to tell me what number would be at the location the user inputs:
import java.util.Scanner; //import Scanner
public class Main {
public static void main(String[] args) {
System.out.println("enter number");
Scanner input = new Scanner(System.in);
int n = input.nextInt();
Fibonacci fibonacci_test = new Fibonacci();
fibonacci_test.Recursivefibonacci(n);
}
}
Here is my Fibonacci code that I have:
public class Fibonacci {
//Fn=F(n-1)+F(n-2)
//The recursive Fibonacci method
public int Recursivefibonacci(int n) {
if(n==0) {
return 0;
} if(n==1) {
return 1;
}else {
int fib = Recursivefibonacci(n-1)+Recursivefibonacci(n-2);
return fib;
}
}
}
I cannot get this thing to print anything. How can I fix this?
It's because you're not printing anything else.
Your method doesn't print anything (just returns a value), and your main doesn't print anything (aside from "enter number").
You can try changing: fibonacci_test.Recursivefibonacci(n); to println (fibonacci_test.Recursivefibonacci(n));
It would be more appropriate to return Recursivefibonacci(n-1)+Recursivefibonacci(n-2);rather than storing it in a variable.
I did this in python, you can have a look, try to adapt it to java, this might help you. Recursivity can be a headache but seems good.
def fib(n):
if n == 0:
return 0
if n <= 1:
return 1
res = (fib(n-1)+ fib(n-2))
return res
///////
Probably your code will look somehow like this:
public int Recursivefibonacci(int n) {
if(n == 0){
return 0;
}
if(n <= 1) {
return 1;
}
int fib = Recursivefibonacci(n-1)+Recursivefibonacci(n-2);
return fib;
}
Try it! and let me know if it worked.

Why does this while loop never terminate?

I am really stuck on understanding this one concept. I had a while loop from one of my exams, and even though I know what prints, I don't know why.
Here is the code:
class Test {
public static void xMethod(int length) {
while (length > 1){
System.out.print((length - 1) + " ");
xMethod(length-1);
}
}
public static void main(String[] args){
xMethod(5);
}
}
Because length is never updated.
while (length > 1){
System.out.print((length - 1) + " ");
xMethod(length - 1);
length--;
}
As the other answer have point it out, you need to decrements the length variable to fix your current problem with length = length - 1 or length--. (I let my "colleague" answer to explain it better).
My answer is mostly about you usage of a recursive method.
What you probably want is simple an if condition. The recursion will act as loop.
public static void xMethod(int length) {
length--;
System.out.print((length) + " ");
if (length > 1){
xMethod(length);
}
}
xMethod(5) > 4 3 2 1
public static void xMethod(int length) {
length--;
if (length > 1){
xMethod(length);
}
System.out.print((length) + " ");
}
xMethod(5) > 1 2 3 4
Length is not changing at all
class Test {
public static void xMethod(int length) {
while (length > 1){
System.out.print((length - 1) + " ");
xMethod(length-1);
//need to change the length here
}
}
public static void main(String[] args){
xMethod(5);
}
The important thing to add here is to understand how the assignments work in Java.
The value of length is not changed because when you pass a value in the method and it goes in the while loop, the loop stops when the condition stops but not the recursion xMethod(length-1); you have used. That's why even if you add length-- it will not print what you desire.
So for the program to work properly, you have to
Assign value to length variable
Change or remove the recursion.
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
And once you go through the link, you will understand the why the value is not changing.
Note: From the link you come to know that length-- is equal to length = length -1, so basically we have to assign the updated value to length variable.
length is always have the value 5. you should replace length-1 by length--.
class Test {
public static void xMethod(int length) {
while (length > 1){
System.out.print((length--) + " ");
xMethod(length);
}
}
public static void main(String[] args){
xMethod(5);
}
}

Trouble Understanding the Recursion Here

Can someone please help to explain to me why this ends up in an infinite recursion loop?
The variable length reaches the value 1 but for some reason the loop is still entered even though the loops condition is while (length>1).
I've tried printing values and running it over and over again, maybe I'm missing something more obvious or someone can explain this more simply. Thanks.
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
while (length > 1) {
System.out.print((length - 1) + " ");
xMethod(length - 1);
}
}
Additional info.
When I dubugged this code :
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
while (length > 1) {
System.out.print((length - 1) + " ");
xMethod(length - 1);
}
System.out.println("Coming out of while");
}
Below is the output :
4 3 2 1 Coming out of while
1 Coming out of while
1 Coming out of while
1 Coming out of while
1 Coming out of while
1 Coming out of while
1 Coming out of while
//repeated Infinite times
After coming out of while loop why it is going back in the same while loop with length as 2?
Edit: I appreciate all of your responses and understand that if I wanted to code something like this I would probably us an if statement as most recursive methods do but this is simply a question of me perhaps not understanding how the scope or call stack works. If I'm correct the while loop block holds on to the value of length as 2 no matter what happens outside of that block?
You are doing 2 things here. When you are writing a recursive code, you always need to think when the when code will end. Your code does not have a end case.
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
System.out.println("Method Start "+ length);
while (length > 1) {
System.out.println("Inside while "+ length);
xMethod(length - 1);
}
System.out.println("Method End "+ length);
}
}
Now this code produces the following output:
Method Start 5
Inside while 5
Method Start 4
Inside while 4
Method Start 3
Inside while 3
Method Start 2
Inside while 2
Method Start 1
Method End 1
Inside while 2
Method Start 1
Method End 1
Inside while 2
Method Start 1
Method End 1
Inside while 2
Method Start 1
Method End 1
.
.
As you can clearly see,
Inside while 2
Method Start 1
Method End 1
is repeated again and again.
So what this means is, when the length is 2, the following will happen.
while (2 > 1) {
System.out.println("Inside while "+ length);
xMethod(1);
}
The output for this is
Inside while 2
Now, xMethod(1) doesn't even enter the while loop, so this will be printed.
Method Start 1
Method End 1
But you should now understand that while(2>1) is again execute because the length has not changed and it is still 2.
while (2 > 1){
System.out.println("Inside while "+ length);
xMethod(1);
}
goes on and the loop continues.
Because you are not updating the value of length in the current method. The value is just decremented when sending to the method.
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
while (length > 1) {
System.out.print((length) + " ");
xMethod(length);
length--;
}
}
The variable length never reaches the value 1 in any loop, you mix two design and i think you need on of them, recursive method or loop.
first design:
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
System.out.print((length - 1) + " ");
if(length > 1)
xMethod(length - 1);
}
}
another way:
public static void main(String[] args) {
xMethod(5);
}
public static void xMethod(int length) {
while (length > 1) {
System.out.print((length--) + " ");
}
}
you can select one of these, it depend on your design.
if it's not your answer, please write your expect output.
because when length reaches 2 xMethod(2) is called and therefore xMethod(1) follows, when xMethod(1) ends, since length is still 2 it again calls xMethod(2) and the this calls xMethod(1) it repeates..
to fix it, use return after xMethod(length - 1);
public static void main(String[] args){
xMethod(5);
}
public static void xMethod(int length) {
while (length > 1) {
System.out.print((length - 1) + " ");
xMethod(length - 1);
return;
}
System.out.println("Coming out of while");
}

Why does my code only execute once

I want to print all the even numbers, but it only gives me 0!!
public class DataType {
public static void main(String[] args){
int number=0;
int max=20;
do{
System.out.println("this is an even number"+ number);
number++;
}while(number<=max&&EvenNumber(number));
}
public static boolean EvenNumber(int a)
{
if((a%2)==0)
{
return true;
}else
return false;
}
}
that is what your condition states: do while both conditions meet!, afters doing number++ for the 1st time the left side of the condition returns false and your loop is done!
you mean for sure:
do {
if (isEvenNumber(number)) {
System.out.println("this is an even number" + number);
}
number++;
} while (number <= max);
remember, following code means
while(number <= max && EvenNumber(number))
while BOTH conditions meet...
After number++;, number becomes 1, and thus the condition becomes false, and the loop terminates.
I assume, you wanted to do
do {
if (isEvenNumber(number)) System.out.println(number);
number++;
} while(number<=max);
Because in your code, If number is equals to 1, while condition is false
If you intend to find all even number between [0, 20] you may change your code to this version:
public static void main(String[] args) {
int max=20;
for (int number = 0; number <= max; number++) {
if (number % 2 == 0) {
System.out.printf("%d is an even number.\n", number);
}
}
}
This reads like:
start with number 0
while number not past 20
if number is even print it
continue with next number
Because in the second iteration the loop will exit.
if you want to print even numbers then the code should be
do{
if(EvenNumber(number)) {
System.out.println("this is an even number"+ number);
}
number++;
}while(number<=max );

Can someone please go through how this program works. Im new to java

Please explain how this converts decimal to binary:
import java.util.*;
public class decimalToBinaryTest {
public static void main(String[] args) {
int number;
Scanner in = new Scanner(System.in);
System.out.println("Enter a positive interger");
number = in.nextInt();
if (number < 0) {
System.out.println("Not a positive interger");
}
else {
System.out.print("Convert to binary is: ");
System.out.print(binaryform(number) + ".");
}
}
private static Object binaryform(int number) {
int remainder;
if (number <= 1) {
System.out.print(number);
return null;
}
remainder = number % 2;
binaryform(number >> 1);
System.out.print(remainder);
{
return " ";
}
}
}
I mainly don't get the bit in private static object. Or the return " ". I really don't see how it does but it works. If you enter 10 it displays: Convert to binary is: 1010.
Do I need the >> 1 or can it be *0.5
There are two important moments in this code:
binaryform(number >> 1);
first: recursion. Call function from this function (foo() {foo();}
second: bitwise. >>1 - shift number for 1 bit, it's the same to devide by 2.
every recursion iteration, code devide number by 2 and print reminder AFTER recursion function works (from last to first). It's like:
{
{
{
{
print inner (fourth iteration
}
print before inner (third iteration)
}
print before before inner (second iteration)
}
print outer (first iteration)
}

Categories