问题
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