114k views
1 vote
What is output? public class MathRecursive { public static void myMathFunction(int a, int r, int counter) { int val; val = a*r; System.out.print(val+" "); if (counter > 4) { System.out.print("End"); } else { myMathFunction(val, r, counter + 1); } } public static void main (String [] args) { int mainNum1 = 1; int mainNum2 = 2; int ctr = 0; myMathFunction(mainNum1, mainNum2, ctr); } }

a) 2 4 8 16 32 End
b) 2 2 2 2 2
c) 2 4 8 16 32 64 End
d) 2 4 8 16 32

1 Answer

3 votes

Answer:

The output of the program is:

2 4 8 16 32 64 End

Step-by-step explanation:

See attachment for proper presentation of the program

The program uses recursion to determine its operations and outputs.

The function is defined as: myMathFunction(int a, int r, int counter)

It initially gets the following as its input from the main method

a= 1; r = 2; counter = 0

Its operation goes thus:

val = a*r; 1 * 2 = 2

Print val; Prints 2

if (counter > 4) { System.out.print("End"); } : Not true

else { myMathFunction(val, r, counter + 1); }: True

The value of counter is incremented by 1 and the function gets the following values:

a= 2; r = 2; counter = 1

val = a*r; 2 * 2 = 4

Print val; Prints 4

else { myMathFunction(val, r, counter + 1); }: True

The value of counter is incremented by 1 and the function gets the following values:

a= 4; r = 2; counter = 2

val = a*r; 4 * 2 = 8

Print val; Prints 8

else { myMathFunction(val, r, counter + 1); }: True

The value of counter is incremented by 1 and the function gets the following values:

a= 8; r = 2; counter = 3

val = a*r; 8 * 2 = 16

Print val; Prints 16

else { myMathFunction(val, r, counter + 1); }: True

The value of counter is incremented by 1 and the function gets the following values:

a= 16; r = 2; counter = 4

val = a*r; 16 * 2 = 32

Print val; Prints 32

else { myMathFunction(val, r, counter + 1); }: True

The value of counter is incremented by 1 and the function gets the following values:

a= 32; r = 2; counter = 5

val = a*r; 32 * 2 = 64

Print val; Prints 64

if (counter > 4) { System.out.print("End"); } : True

This prints "End"

So; the output of the program is:

2 4 8 16 32 64 End

User Aram Gevorgyan
by
4.3k points