2
#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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
C-flow
  • 19
  • 1
  • 3
  • https://ideone.com/Aerc5T – Retired Ninja Sep 28 '17 at 04:50
  • 1
    You need one loop to count from 1 to the limit of your range; you need an inner (nested) loop to determine the Collatz sequence for each such value. You need to improve your printing to better identify when you start a new value (output a newline after completing the sequence). Or, better, write a function that prints the Collatz sequence for the number passed to it, and then have the main program call that function for each value in the range 1..limit. You should print the comma before the numbers (except the first, which would be probably be printed separately anyway). – Jonathan Leffler Sep 28 '17 at 05:28

1 Answers1

1

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;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189