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

int main(void)

{
    do
    {
        int n=get_int("positive no:");
    }
    while(n<=0);

    for( int i=0;i<n;i++)
    {
        printf("#\n");
    }

}
2

Your problem is a scope issue.

The way you declare n, it ceases to exist after you leave the loop's body. Which means when you enter the while(n<=0), it no longer is.

To prevent this, place a int n; before your loop, and just n = get_int(... within.

Make sure to not have int n = get_int(... within the loop as well, as you would have two variables of name n, the inner one shadowing the outer one (means within the loop you wouldn't be able to assign to the outer one).

Examples:

  1. Left scope

    if (0 == 0)
    {
        int n = 23; // declared within a code block
        printf("%i\n", n); // prints 23
    }
    printf("%i\n", n); // Compiler error: n does not exist!
    
  2. Shadowing outer variable

    int n = 42; // first variable named "n"
    if (0 == 0)
    {
        int n = 23; // another variable of same name
        printf("%i\n", n); // prints 23
    }
    printf("%i\n", n); // prints 42
    
  3. Correct scope

    int n; // declared before the code block
    if (0 == 0)
    {
        n = 23;
        printf("%i\n", n); // prints 23
    }
    printf("%i\n", n); // prints 23 as well
    

The while or if does not matter, the curly braces create a scope (variable declarations within a loop head, often used for counting in a for loop, also have their own scope). You could even use the curly braces without any keyword, not sure why one would do that.

| improve this answer | |
  • #include <cs50.h> #include <stdio.h> int main(void) int n; { do { int n=get_int("positive no:"); } while(n<=0); for( int i=0;i<n;i++) { printf("#\n"); } } should i add like this – manish_rocks Mar 14 '18 at 18:29
  • Put int n; before do and remove the int from the do..while loop. That's all to fix the error. – Blauelf Mar 15 '18 at 7:27
  • thanks i got it – manish_rocks Mar 22 '18 at 9:50

You must log in to answer this question.

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