Skip to main content

GATE CSE 2026Programming in C › Recursion & Program TracingVerified

GATE CSE 2026 PYQ: Consider the following ANSI-C function. int func ( int start , int end ){ int length = end + 1 - start ; if…

Consider the following ANSI-C function.

  1. int func(int start, int end){
  2. int length=end+1-start;
  3. if((length<1)||(start<0)||(end<0)){ return(0); }
  4. if(length%3==0){
  5. return(func(start+1, end));
  6. }else if(length%3==1){
  7. return(1+func(start, end-1));
  8. }else {
  9. return(func(start+2, end));
  10. }
  11. }

The maximum possible value that can be returned from this function is ______\_\_\_\_\_\_. (answer in integer)

Note: Ignore syntax errors (if any) in the function.

    Answer

    1

    Approach

    Track only the current length L = end + 1 - start and its remainder modulo 3. Each recursive call decreases L by 1 or 2, and the branch chosen depends solely on L mod 3. The function adds 1 only when L mod 3 = 1, which can happen at most once before the remainder leaves 1 forever.

    The only branch that increases the returned value is the L%3==1 case, which adds 1. After that branch, the new length has remainder 0, and the subsequent remainder sequence cycles only between 0 and 2, so another +1 is impossible. Hence the maximum possible return value is 1.

    Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.