Home > Software design >  Unable to understand how the program is being executed
Unable to understand how the program is being executed

Time:05-17

enter image description hereI saw an question paper of NET examination and found the following java question

public class First {

  public static int CBSE(int x) {
    if (x < 100) x = CBSE(x   10);
    return (x - 1);
  }

  public static void main(String[] args) {
    System.out.print(First.CBSE(60));
  }
}

I am unable to understand the if condition. I ran the program on my machine and it returns 95 without any error. Can anyone please demonstrate how the program is executed?

CodePudding user response:

Assuming the 10 on the second line is x

CBSE(60)
=CBSE(70)-1
=CBSE(80)-1-1
=CBSE(90)-1-1-1
=CBSE(100)-1-1-1-1
=99-1-1-1-1
=95

CodePudding user response:

CBSE(60) ->

             60<100 so, x=CBSE(70)

                   ...................................80

                                       ............................................90

                                              ......................................................100    

                                                                                 100  is not < 100  SO CBSE(100) Returns 100-1=99

        cbse(90) returns 98

  cbse(80) returns 97

cbse(70)returns 96

cbse(60) returns 95

therefore the final result is 95

CodePudding user response:

You use a recursive function.
Any new call is stacked while x<100.
If you put trace inside BSE function you will see :

entering CBSE with 60
entering CBSE with 70
entering CBSE with 80
entering CBSE with 90
entering CBSE with 100
exiting CBS with 99
exiting CBS with 98
exiting CBS with 97
exiting CBS with 96
exiting CBS with 95
95
  • Related