I'm new to coding and I've been having trouble with Lab 1. I was able to get the program to properly ask for a start and end size, but the number of years is not listed.

Here's an example:

population/ $ make population
population/ $ ./population
 Start Size 9
 End Size 10

And other times, I get multiple outputs of years, such as:

population/ $ make population
population/ $ ./population
 Start Size 9
 End Size 19
 Years: 9  Years: 10  Years: 11  Years: 12  Years: 13  Years: 14  Years: 15  Years: 16  Years: 17

I think I'm getting confused on how to run the loop so that the start size reaches the end size, while also keeping a counter of the number of years it takes.

Here's the code that I have so far:

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

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


    s = get_int ( " Start Size " );

     while ( s < 9 || s % 1 != 0 ); // No less than 9 and no decimals

    // TODO: Prompt for end size
    int e;

    do // Makes sure minimum is smaller than maximum

    e = get_int ( " End Size " );

    while ( e < s || e % 1 != 0 ); // last part is for no decimals

    if ( s == e ) // If start and end are the same

    { printf ( " Years: 0 " ) ;}

    // TODO: Calculate number of years until we reach threshold

    int n;

    int y;

    for ( n = s ; n + ( trunc ( n / 3 ) - trunc ( n / 4 ) ) < e ; n++ )

    // TODO: Print number of years

    printf ( " Years: %i " , n );




1 Answer 1


I see two serious problems here.

First, the print statement is inside the for loop, so you're going to print something on every pass through the loop, or nothing at all if the loop doesn't execute. The print statement should follow the loop.

Next, you've intermixed the calculation for the population with the variable that tracks the years. The population needs to be calculated in a separate variable.

BTW, what happens if the years value is zero? It looks like it could print two statements about the value of years. When code is doing something very similar more than once, it's a signal that you should see if there's a way to consolidate and simplify the code. In this case, is there a way to write the code so that the special case (or corner case, as it is sometimes called) can be handled by the code that handles the general case?

Another alternative would be to include a return statement if the code is done processing after the special case and there's no need to do anything else.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .