Samjohns081998
Samjohns081998

Reputation: 141

Loops running infinitely for big inputs

I am self learner, I am working on a population growth problem, and I came across the issue of loop running infinitely when I enter a big ending number that I want to reach.

#include <cs50.h>
#include <stdio.h>

int main(void) {
    // TODO: Prompt for start size
    int n;

    do {
        n = get_int("Enter the starting size of your llamas: ");
    } while (n <= 8);

    // TODO: Prompt for end size
    int j;

    do {
        j = get_int("Enter the Ending size of your llamas: ");
    } while (j <= n);

    // TODO: Calculate number of years until we reach threshold
    int k = 0;

    do {
        n = n + (n/3) - (n/4);
        printf("The number is %i\n", n);
        k++;
    } while (n != j);

    // TODO: Print number of years
    printf("The number is %i\n", k);
}

The answer is supposed to be the number of years it takes to reach the end size llamas, but I am not able to put in big numbers of end size, can you help me figure out what is wrong, maybe in my math or a sign. Thanks in advance.

Upvotes: 0

Views: 71

Answers (1)

chqrlie
chqrlie

Reputation: 145277

For large numbers, n is incremented by more than 1 at each iteration, so it is possible than it becomes larger than j without being equal to it first.

Change the test while(n != j); to while(n < j);

Upvotes: 2

Related Questions