Knowee
Questions
Features
Study Tools

What will be the output of the following code ?public static void print(int n){ if(n < 0){ return; } if(n == 0){ System.out.println(n); return; } print(n--); System.out.print(n+" ");}public static void main(String[] args) { int num = 3; print(num);

Question

What will be the output of the following code ?public static void print(int n){ if(n < 0){ return; } if(n == 0){ System.out.println(n); return; } print(n--); System.out.print(n+" ");}public static void main(String[] args) { int num = 3; print(num);

🧐 Not the exact question you are looking for?Go ask a question

Solution

The code you provided will result in a StackOverflowError. This is because the line print(n--); is supposed to decrease the value of n by 1, but the decrement operator (--) is used as a post-decrement, not pre-decrement. This means that n is passed into the next function call before it is decremented, causing an infinite recursive loop.

If you want to print the numbers from n to 0, you should use print(--n); instead of print(n--);. This way, n is decremented before it is passed to the next function call.

Here is the corrected code:

public static void print(int n){
    if(n < 0){
        return;
    }
    if(n == 0){
        System.out.println(n);
        return;
    }
    print(--n);
    System.out.print(n+" ");
}

public static void main(String[] args) {
    int num = 3;
    print(num);
}

This will output: 0 1 2

This problem has been solved

Similar Questions

Select the correct answer What will be the output of the following Java code?class evaluate {  public static void main(String args[])     {   int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};   int n = 8;      n = arr[arr[n] / 4];   System.out.println(arr[n] / 4);    } }Options1230

What output is displayed when the following code is run?int num1 = 11;int num2 = 18;int num3 = 15;int num4 = 0;if (num1 > num3) { num4 = 4;} else { if (num2 > num3) { num4 = 5; }}System.out.println(num4);50424

What will be the output of the following program?public class Test{ public static void main(String args[]){ int i = 0, j = 5 ; for( ; (i < 3) && (j++ < 10) ; i++ ){ System.out.print(" " + i + " " + j ); } System.out.print(" " + i + " " + j ); }}0 6 1 7 2 8 3 80 6 1 7 2 8 3 90 6 1 5 2 5 3 5Compilation Erro

e correct answerWhat is the output of the following Java program?class Main { public static void main(String args[]) { final int i; i = 20; i = 30; System.out.println(i); }}

What will be the output of the following Java program?class java   {    public static void main(String args[])    {      int var1 = 3;       int var2 = 8;      if ((var2 = 2) == var1)        System.out.print(var2);      else         System.out.print(++var2);    }   }Options3421

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.