-1
    // Define the recursive function.
    int collatz(int p1)
    {
        // While Loop Starting
        while (p1>1)
        {
      //when the number is even
        if(p1%2==0)
        {
            p1 = p1/2;
            printf("%d ", p1);
        //using recursion
            return collatz(p1);
        }
        // Case where number is odd.
        elseif
        {
            p1 = 3*p1+1;
           //print function
            printf("%d ", p1);
           //using recursion
            return collatz(p1);
        }
        }
     }  
    // Main body.
    int main()
    {
       // Declare the variable and initialized it.
      int p1= 4;
      //print function
     printf("User Entered value  : %d\n", p1);
       // Display the number 
        printf("%d\n", collatz(p1));
        //End
        return 0;
    }

Output: I am getting the Output as : 2 ,1, 1 I should not get the last number 1 repeated.Could you please correct me where i have done mistake.Please do the needful.

chandu
  • 27
  • 4

1 Answers1

0

You should always enable warnings when you compile a C or C++ program. Had you done do, the compiler would have warned you that your function collatz could terminate without returning a value. (What happens if the argument is 1?)

That's undefined behaviour, and so is the use of the possibly-nonexistent return value in your main function.

So it is just a quirk of chance that it happens to print 1 in main. But whatever it printed would be wrong because you seem to expect the output to be limited to what is printed in collatz.

You might try playing computer and executing your function with a pencil and paper. It won't take very long. Of course, you could also use a debugger.

rici
  • 234,347
  • 28
  • 237
  • 341
  • I am working un Linux environment.I am new to C programming.I am not aware of debugging in linux environment in vmware machine. – chandu May 29 '16 at 00:02
  • @chandu: yes, I suspected as much, which is why I suggested using a pencil and paper. But if you are serious about learning how to program, you will eventually have to kearn how to use a debugger. – rici May 29 '16 at 00:05