Demi Demi - 4 months ago 18
C Question

error: use of undeclared identifier

I'm trying to run this code, but I keep getting:

:21:20: error: use of undeclared identifier 'r'
for(int s = h - r; s > 0;s--)


but I can't seem to figure out why I'm getting the error. Can anyone help me out here?

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

int main(void)
{
int h;
do
{
printf("please give me a positive int between 1 and 23: ");
h = GetInt();
}
while (h < 1 || h > 23);
//get int and store it


for(int r = 0; r < h; r++)
{
printf("#");
}

for(int s = h - r; s > 0;s--)
{
printf(" ");
}
}

Answer

You'd better declare r right after main begins as in your current code you're declaring r only for the for loop.

int main() {
    int r=0, h=0;

    // add other code here
    // don't forget h=GetInt()

    for(r = 0; r < h; r++)
    {
        printf("#");
    }

    for(int s = h - r; s > 0;s--)
    {
        printf(" ");
    }      
}