Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading