Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this second loop have no initialization? And why does it print five stars?

Tags:

c

for-loop

This program produces this output:

*******
 *****
  ***
   *

Here's the code:

#include  <stdio.h>
int main(void)
{
 int i, j;
 for (i = 1; i <= 5; i++)
 {
  for (j = 1; j < i;j++)
   printf(" ");
  for (; j <= 8 - i;j++)
   printf("*");
  printf("\n");
 }
 return 0;
}

What's the meaning of for (; j <= 8 - i;j++)? There is no initialization step and also don't understand why there is only five * on the second line.

like image 644
Sungmin Kim Avatar asked Nov 25 '25 17:11

Sungmin Kim


1 Answers

For loops don't actually need to have an initialization statement. Many loops choose to include one, but it's not strictly necessary. Consequently, you can think of that loop as saying "we don't need to do anything special here for initialization."

As for why there are five stars on the second line, let's look at this part of the code:

for (j = 1; j < i;j++)
 printf(" ");
for (; j <= 8 - i;j++)
 printf("*");

On the second iteration, i is equal to 2. When the first loop runs, it will print out a single space character. The loop stops running when j < i is no longer true, so when it finishes running, the value of j will be 2. Therefore, the second loop will run for j =2, 3, 4, 5, 6, stopping when j = 7. That's why you see five stars.

Hope this helps!

like image 139
templatetypedef Avatar answered Nov 28 '25 17:11

templatetypedef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!