C-flow
C-flow

Reputation: 19

Collatz sequence from 1 to a given value

#include <stdio.h>

int main() {
    int rangeValue;
    int x;
    printf("Please input a number to be considered in the range:\n");
    scanf("%d", &rangeValue);
    while (rangeValue != 1) {
        x = rangeValue;
        if ((x % 2) == 0) {
            x = x / 2;
            printf("%d,", x);
        } else {
            x = (3 * x) + 1;
            printf("%d,", x);
       }
       rangeValue--;
    }
    return 0;
}

My goal is to do the Collatz sequence of every number from 1 to the number I give to rangeValue. I expected this to work. Can anyone help me make it work?

Upvotes: 2

Views: 2047

Answers (1)

chqrlie
chqrlie

Reputation: 144949

You are mixing the range of sequences to print, the maximum number of iterations and the current number in the sequence.

Here is how to fix the code:

#include <stdio.h>

int main(void) {
    int rangeValue;
    printf("Please input a number to be considered in the range:\n");
    if (scanf("%d", &rangeValue) != 1)
        return 1;
    // iterate for all numbers upto rangeValue
    for (int n = 1; n <= rangeValue; n++) {
        printf("%d", n);
        for (long long x = n; x != 1; ) {
            if ((x % 2) == 0) {
                x = x / 2;
            } else {
                x = (3 * x) + 1;
           }
           printf(",%lld", x);
        }
        printf("\n");
    }
    return 0;
}

Upvotes: 1

Related Questions