#include #define MAX 100000 int main () { int limit, n, num, maxH, h; int steps[MAX] = {}; // initialize array to all zeros // take input limit printf("How many numbers to check? "); scanf("%d", &limit); printf("\nCollatz Sequences:\n"); for ( n = 0; n < limit; ++n ) { num = n+1; // n-th number is n+1 while ( num > 1 ) { // generate the collatz sequence for a number printf("%d -> ", num); if ( num % 2 ) num = 3 * num + 1; // odd case else num = num / 2; // even case ++steps[n]; // calculate number of steps to converge to 1 } printf("1\n"); } printf("\nThe Histogram:\n"); // find maximum height/steps maxH = steps[0]; for ( n = 1; n < limit; ++n ) if ( maxH < steps[n] ) maxH = steps[n]; for ( n = 0; n < limit; ++n ) // print a horizontal line printf("----"); printf("\n"); for ( h = maxH; h > 0; --h ) { // for each row upto maxH for ( n = 0; n < limit; ++n ) { // for each column upto limit if ( h > steps[n] ) printf(" "); // histogram below this h, so space to be printed else printf(" H "); // histogram till or above this h, so H to be printed } printf("\n"); } for ( n = 0; n < limit; ++n ) // print a horizontal line printf("----"); printf("\n"); for ( n = 0; n < limit; ++n ) // print the numbers printf(" %2d ", n+1); printf("\n"); for ( n = 0; n < limit; ++n ) // print the number of steps taken to converge printf("(%2d)", steps[n]); printf("\n"); return 0; }