1

I'm having problems compiling my code due to "undeclared identifiers", despite the fact that I have declared every single one of them. I will copy my code and I'll be really grateful if any of you guys gives me a tip. I tried to combine loops and modulo:

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

int main(void)

{
    int f = 1;
    int n = 5;
    int m = 10;
    int c = 25;

    printf("How much change is owed?\n");

    float t = GetFloat();
    int q = t * 100;

    do
    {
        int p = 0;
        int i = q - p * c;
        p = p + 1;
    }
    while (i > 0);

    i = t % c;

    do
    {
        int r = 0;
        int o = i - r * m;
        r = r + 1;
    }
    while (o > 0);

    o = i % m

    do
    {
        int l = 0;
        int y = o - l * n;
        l = l + 1;
    }
    while (y > 0);

    y = o % n;

    do
    {
        int u = 0;
        int k = y - u * f;
        u = u + 1;
    }
    while (k > 0);

    printf("%i\n", p + r + l + u);
}

Thank you in advance. P.S. I would also like to specify that I will later try to figure out the negative input code that I need to add - right after I'm sure the rest is right.

1
2

Well, you did, but you didn't declare the identifiers. The problem is scope. Numerous variables are being used outside of the scope where they exist. When a variable is declared, it is only valid inside the immediate pair of curly braces that surround it. Outside of those curly braces, the variable doesn't exist. For example, look at the following snippet from your code:

do
{
    int p = 0;
    int i = q - p * c;
    p = p + 1;
}
while (i > 0);

The vars p and i exist inside of the do loop code block, but not outside. The first error is the while statement where you try to use the no-longer-existing variable i. Also, after that last curly brace, q no longer exists.

This is the general problem that the code has. If you were to declare these vars at the beginning of the program, along with f, n, etc., they would be valid through the code - or at least if you had declared them outside of the immediate curly braces.

As a side note, best practice for single letter variable names is to use them only for loop counters. For other vars, it is better to use more descriptive names, like penny, nickel, dime, change, etc., so that anyone reading the code can easily understand what they represent. Also, add comments to give an idea what each part of the code is doing and what is expected. If you don't believe this, come back to this code in 2 months and try to remember what you did. ;-) Better to break bad habits before they start.

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 .