Week 1 - mario exercice. Into the program below , I do not understand why

while (n<1)

As width is a positive value, n shouldn't be >1 ?


#include <stdio.h>

#include <cs50.h>

int main(void)


    int n;



        n = get_int("Width: ");


    while (n<1);

    for (int i = 0; i < n; i++)









Yes, the desired user input should be a positive integer. The idea here is that the loop should repeat when the user inputs a non-positive number, ie, n<1. If they enter a positive, then all is well and there's no need to repeat. The loop only repeats if the user input is bad or <1.

Think of it as testing for something undesirable to trigger the loop.

As a separate issue, even if you wanted the loop to repeat for positive numbers, n>1 would be bad because it would exclude 1. It would need to be n>=1.


I don't think you have understood how a DO-WHILE loop works. The difference with other loops is that THIS is going to be executed at least once, regardless of the condition we impose. With this we get that the user gives us the height, it is assumed that a positive integer value. But what happens if the user does not collaborate, that is, they enter a negative value? Well, after introducing the height, the following line of the program will be executed (while (n <1)), and the program enters the loop again, since the condition is true, which prompts the user for the height, and this will be so until the value is positive.

You must log in to answer this question.

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