for循环内的for循环工作时没有大括号? [英] For loop inside for loop works without a curly brackets?

查看:108
本文介绍了for循环内的for循环工作时没有大括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在没有花括号的情况下,for循环中的for循环如何工作?如您所见,在while循环中也有两个for循环,但是它们都需要大括号,但是在嵌套循环的主语句中,不需要大括号吗?

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;
}

推荐答案

此代码格式不正确,从而隐藏了循环的实际作用:

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");
}

内部循环不需要花括号,因为它仅执行一条语句( printf 调用).但是,无论如何,最好将所有循环体和条件表达式放在大括号中.

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.

这篇关于for循环内的for循环工作时没有大括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆