Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

411
Views
Why does this function return 83 and not 5 when we call function(2)?

When I run this function by inputting 2 and I do not understand why it returns 83 and not 5 since it should call function(1) in the else statement and then the if statement should get executed and the function should return 5.

public static int function(int y) {
    if (y == 1)
        return 5;
    
    function(y - 1);
    y = y + 1;
    
    return 83;
}
over 4 years ago · Santiago Trujillo
4 answers
Answer question

0

It returns 83 because you are not using the return value of function(y - 1);
To test it try:

public static int function(int y) {
    if (y == 1)
        return 5;
    else {
        int returnedValue =  function(y - 1);
        System.out.println("un used returned value: "+returnedValue);
        y = y + 1;
        return 83;
    }
}

Change to:

public static int function(int y) {
   if (y == 1)  return 5;
   /*else*/ 
   return function(y - 1); 
}
over 4 years ago · Santiago Trujillo Report

0

With input: y = 2,

else condition will be handled.

function(y - 1);//nothing impact to y
y = y + 1;// y =3
return 83; // but finally return 83

Do you get the point?

over 4 years ago · Santiago Trujillo Report

0

Since you do not return function(y-1), the statement is as good as making the function void (for that call).

So, as soon as the control reaches function(y-1) and eventually leads to calling function(1), you do get 5 but it is not returned to the driver function. What is instead returned is the value 83.

over 4 years ago · Santiago Trujillo Report

0

Check this out:

public static int function(int y) {
    if (y == 1)
        return 5;
    
    function(y - 1);   // you do not use return value
    y = y + 1;

    return 83;         // you always get this return
}

It means that you can replace your function with:

public static int function(int y) {
    return 83;
}

Looks like you want to do smth. like this:

public static int function(int y) {
    return y == 1 ? 5 : function(y - 1);
}

but be careful, because for y < 1 you will have an infinite recursion (StackOverflowError).

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!