MilesLinares
MilesLinares

Reputation: 1

Currently take CS50, having trouble understanding why this works?

int i;
do
{
    i = get_int("height: ");
}
while (i < 1);

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

This code executes in the terminal properly but I don't understand how this part
for(int n = 0; n < i; n++) allows for the user to input a positive integer and it prints the correct amount.

The way I am thinking out it is that the top part gets the users integer and assigns it to i, and it will has until a positive integer is given.
But I don't get how the loop works.

Why does assigning 0 to n and having n be less than i and incrementing n by 1 using n++ give the result of printing the hashes "#" according to the users input?

If anyone could please help me understand it would be greatly appreciated, new to code and C.

Upvotes: 0

Views: 76

Answers (2)

John Bode
John Bode

Reputation: 123558

There are two forms of a for loop in C:

for ( expr1opt ; expr2opt ; expr3opt )
  statement

for ( declaration expr2opt ; expr3opt )
  statement

First, if it’s present, either expr1 or the declaration is evaluated - this expression usually initializes our loop counter or otherwise sets up the thing expr2 tests against. In this case, we’re declaring the counter n and initializing it to 0.

Next, if it’s present, expr2 is evaluated (if it’s not present, a non-zero value is assumed). If the result of the expression is a non-zero value, the loop body is executed. In this case, the loop body is executed if the value of n is less than i.

Finally, expr3 is evaluated. This expression usually updates the loop counter or whatever thing expr2 tests against. In this case, it’s incrementing n by 1.

So the way this particular loop works is:

  1. Declare and initialize n to 0 (declaration)
  2. If n is less than i then go to 3, else go to 6 (expr2)
  3. Print a hash character (statement)
  4. Add 1 to n (expr3)
  5. Go to 2
  6. End loop

Edit

For people asking about the missing semicolon in the second form, a declaration includes a terminating ;:

declaration:
    declaration-specifiers init-declarator-listopt ;

Upvotes: 1

Srishruthik Alle
Srishruthik Alle

Reputation: 488

Ah yes CS50. So basically how this line => for(int n = 0; n < i; n++) checks if the number is positive or not is first lets subsitite 0 to n. So it would be basically => for(int n = 0; 0< i; n++). so that means that i has to be greater than 0. If not the for loop WON'T execute. so if the i value is 5. 0<5 is true so that means that for loop WILL execute.. if the i value is -1. 0<-1 is false so the for loop WON'T execute. if u entered 5 it will repeat 5 times.(if the i value is 5) because you are starting for 0 then incrementing(n++) 5 times.

Upvotes: 0

Related Questions