Problem in a part of 3n+1 problem

I’m just printing the in between integers but the execution is converting into an infinite loop.

#include<conio.h>

#include<stdio.h>
void recur(int l)

{

if(l==1)
    {
        printf("%d ", l);
        return 1;

    }
    if(l%2==0)
    {
        l=l/2;
        printf("%d ", l);
        recur(l);
    }
    if(l%2!=0)
    {
        l=(3*l)+1;
        printf("%d ", l);
        recur(l);
    }

}

int main()

{

int n;
scanf("%d", &n);

recur(n);

return 0;

}

Help.

use else if (l%2!=0)

@mukul_chandel thanks…

Your Function Should Not return any value as it is of void datatype. Using An Else-If Would correct the error of running into an infinite loop.

1 Like

// everything explained in comments

#include<stdio.h>
//#include<conio.h>

int recur(int l)
/* If your function is void, then it should not return any values. But in condt 1, it returns a value. So int will do the job of not sending the program to an infinite loop */

{
if(l==1) // condt 1
{
printf("%d “, l);
printf(”\n\n");
return 0;
/**if you want to use the void data type, instead of return 0; try exit(0); and if you want to use this exit function , give the stdlib.h header
**/
}

 else if(l%2==0) // condt 2
 {
    l=l/2;
    printf("%d ", l);
    recur(l);
 }

 else //if(l%2!=0) // condt 3
 {
     /* 
      * using if means that you are checking the condition once again, after checking the condt 2. 
      * using else if means that you are checking the if condition once (cond 2) and if it is false, then you are comming to this condition (condt 3).
      * moreover you need not use else if. else will do the job. You can use else if in the condt 2
      */
    l=(3*l)+1;
    printf("%d ", l);
    recur(l);
 }

}

int main()

{

int n;
scanf("%d", &n);

recur(n);

return 0;
}

wherever you find / or / please note that they are multi-line comments