Search code examples
ccs50

Can I "i++" inside a function if "int i = 0" is written outside of it?


I'm working on Problem Set 1 2024, to which I wrote a functioning file which answers the problem. Nonetheless, I decided to try to "clean" it a little bit and make it more readable.

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

void coin(int value, int n);

int main(void)
{

    // prompt user for a change value
    int change = get_int("Change owed: ");

    // force prompt for positive integer
    while (change <= 0)
    {
        change = get_int("Change owed: ");
    }

    int i = 0;
    //repeat below line for each coin
    coin(change, 25);
    
    printf("%i\n", i);
}

//returns number of coins for the change value
void coin(int value, int n)
{
    while(value / n >= 1)
    {
        value = value - n;
        i++;
    }
}

Here lies the problem:

"i" is defined in main, outside of coin(), so when I try compiling, I get the unidentified variable error, in my coin() function.

How can I define int i = 0 so that it's used in my coin() function and incremented correctly?

I tried defining int i = 0 inside of coin(), but then my printf("&s\n") in main doesn't recognize i, as it's inside of coin().

I tried defining int i = 0 as a global variable (despite multiple google searches righftfully telling me it was a mistake), and even though it compiles, it is an incorrect solution to the problem.

I tried learning whether some sort of variable definition prototype exists, to no avail.

Now, I've ran out of ideas and don't know if what I want is possible anymore. I know I can submit the working code and be done with it, but I'm trying to be thorough and learn as much as possible in each problem set, exploring all options and trying to write good code that looks good too.


Solution

  • The way to do that is to return the number from the function:

    #include <cs50.h>
    #include <stdio.h>
    
    int coin(int value, int n);
    
    int main(void)
    {
    
        // prompt user for a change value
        int change = get_int("Change owed: ");
    
        // force prompt for positive integer
        while (change <= 0)
        {
            change = get_int("Change owed: ");
        }
    
        //repeat below line for each coin
        int i = coin(change, 25);
        printf("%d\n", i);
    }
    
    //returns number of coins for the change value
    int coin(int value, int n)
    {
        int i = 0;
        while(value / n >= 1)
        {
            value = value - n;
            i++;
        }
        return i;
    }