For loop inside for loop works without a curly brackets?

我的梦境 提交于 2021-02-17 04:51:11

问题


How does a for loop inside for loop works without a curly braces? As you can see there's two for loops inside while loop first too but they require braces but in the main statement in that nested loop no braces are required?

I am confused on that can anyone explain that?

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() 
{
    int n;
    scanf("%d", &n);
    int size=2*n-1;
    int start=0;
    int end=size-1;
    int a[size][size];
    
    while(n != 0)
    {
       for(int i=start; i<=end;i++){
         for(int j=start; j<=end;j++){
           if(i==start || i==end ||  j ==start || j==end)
              a[i][j]=n;
         }
       }
    ++start;
    --end;
    --n;
    }
    
    for(int i=0;i<size;i++){
       for(int j=0;j<size;j++)
          printf("%d ",a[i][j]);
       printf("\n");
    }

    return 0;
}

回答1:


This code is formatted poorly, which hides what the loops are actually doing:

for(int i=0;i<size;i++)
{
    for(int j=0;j<size;j++)
        printf("%d ", a[i][j]);

    printf("\n");
}

The inner loop doesn't need braces since it's only executing one statement (the printf call). However, it's good practice to put all loop bodies and conditional expressions in curly brackets anyway.




回答2:


In c loops and if statements apply only to next statement if they don't have brackets.

In your example this:

for(int i=0;i<size;i++) {
    for(int j=0;j<size;j++)
        printf("%d ",a[i][j]);
    printf("\n");
}

return 0;
}

is equivalent to:

for(int i=0;i<size;i++) {
    for(int j=0;j<size;j++) {
        printf("%d ",a[i][j]);
    }
    printf("\n");
}

return 0;
}



回答3:


How does a for loop inside for loop works without a curly braces?

The for loop syntax in C can be illustrated as follows:

for ( init; condition; increment ) statement

Where statement can be a single statement (e.g., printf("%d ", a[i][j]);) or a compound statement

A compound statement consists of none or more statements enclosed within a set of braces: {}.



来源:https://stackoverflow.com/questions/65999525/for-loop-inside-for-loop-works-without-a-curly-brackets

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!