Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tricky recursive function 007

Tags:

c

recursion

Elo, I got this code snippet from an old exam. It's tricky and I need some help figuring out how it prints "007".

#include <stdio.h>
/* Desmond Llewelyns */
int M(int Q);
int main(void)
 {

   M(9);
   return 0;
 }
int M(int Q)
 {
   if(Q>1) 
     if(M(Q-1)==0)
       printf("%03d\n", Q);

   return Q-6;
 } 
like image 262
user1797030 Avatar asked Dec 21 '22 14:12

user1797030


1 Answers

It is pretty simple.

Number will be printed only if M(Q-1) returns 0 and that happens when value of Q is 7.

And about the zeros, it is because you are asking printf to print the number in 3 positions printing zeros in the begining. printf("%03d\n", Q); Read more here.

like image 131
CCoder Avatar answered Dec 24 '22 00:12

CCoder