Home > Blockchain >  New To C and trying to make a collatz conjecture program but it's not working and i don't
New To C and trying to make a collatz conjecture program but it's not working and i don't

Time:11-18

This is my attempt at a c program which solves the collatz conjecture i am really new to c and would like to know why my code is not working

#include <stdio.h>
int main()
{
    int num = 0;
    int count = 0;
    printf("Enter your number: ");
    scanf("%d", &num);
    while ("%d" != 2,num);{
        if (num %2 == 0)
        {
                num = num / 2;
                printf("%d", num);
                count = count   1;

        }
        else
        {
                num = num * 3   1;
                printf("%d", num);
                count = count   1;
        }
    }

    if (num == 1);
    {
        printf("%d", count);
    }
    return 0;
}

CodePudding user response:

Your syntax is wrong.

The condition in while should be a boolean condition, and num variable should be different than 1. I edit also printfs to be more suggestive and add a new line to them. I excluded the last if condition because it was redundant. When the code finish while loop the num variable will be 1.

I think what you are trying to do is this:

#include <stdio.h>
int main()
{
    int num = 0;
    int count = 0;
    printf("Enter your number: ");
    scanf("%d", &num);
    while (num != 1)
    {
        if (num %2 == 0)
        {
                num = num / 2;
                printf("num = %d\n", num);
                count = count   1;

        }
        else
        {
                num = num * 3   1;
                printf("num = %d\n", num);
                count = count   1;
        }
    }

    printf("count = %d", count);
    return 0;
}
  • Related