Search code examples
ccs50

C code does not continue running in vscode or ide


I'm doing cs50 code about calculating the population of llamas but it stops in the middle and does not return any thing. the code asks the user to enter number of start size and end size then calculate how many years it needs to reach the end size

note 1: the code uses <cs50.h> header.

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

int main(void)
{
    // TODO: Prompt for start size
    int start_size;
    do
    {
        start_size = get_int("enter the start size\n");
    }
    while (start_size < 9);

    // TODO: Prompt for end size
    int end_size;
    do
    {
         end_size = get_int("enter the end size\n");
    }
      while (end_size < start_size);

    // TODO: Calculate number of years until we reach threshold
    int years = 0;
    do
    {
        start_size = start_size + (start_size/3);
        start_size = start_size - (start_size/4);
        years++;
    }
    while (start_size < end_size);

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

note 2: I tried to execute the code in online IDE after replacing the get_int with scanf and still not work


Solution

  • The OP has not implemented the actual problem statement that uses the year's starting population for BOTH growth AND shrinkage calculations.)

    The problem is here:

            start_size = start_size + (start_size/3);
            start_size = start_size - (start_size/4);
    

    This implements the expression: n = 4/3 * n * 3/4 which any kid will tell you is equivalent to
    n = 12/12 * n, meaning no increase in population.

    The simple fix is NOT using the lvalue of the 1st statement in the 2nd statement. Perform the entire calculation in a single assignment statement:

            start_size = start_size + (start_size/3) - (start_size/4);
    

    Here, the 3 appearances of start_size on the right all have the same value; the current year's starting population.

    The minimum of 9 llamas to start ensures that the herd will grow over time. A smaller seed population will not get traction (an increase of at least 1) and will not grow.

    EDIT:
    Simplified:

            int incr = (start_size/3); // increase by 1/3
            int decr = (start_size/4); // decrease by 1/4
            start_size = start_size + incr - decr;