嵌套for循环的说明

时间:2017-10-18 19:58:11

标签: c for-loop

您可以请某人向我解释以下循环如何打印#include <stdio.h> int main() { int x, y, n; n = 0; for (x = 0; x < 10; x++) for (y = 0; y < x; y++) n++; printf("%d\n", n); } 。我想我并不完全理解这些嵌套循环是如何工作的:

sip:jack@example.com?myHeader=blah

1 个答案:

答案 0 :(得分:6)

尝试扩展第一个循环,帮助自己理解。如果你这样做,你会得到这样的代码:

#include <stdio.h>  
int main() { 
    int x, y, n;
    n = 0;

    /* x=0 */
    for (y=0; y<0; y++)
        n++; /* doesn't get hit n=0 */

    /* x=1 */
    for (y=0; y<1; y++)
        n++; /* gets hit once n=1 */

    /* x=2 */
    for (y=0; y<2; y++)
        n++; /* gets hit twice n=3 */

    /* x=3 */
    for (y=0; y<3; y++)
        n++; /* gets hit three times n=6 */

    /* x=4 */
    for (y=0; y<4; y++)
        n++; /* gets hit four times n=10 */

    /* x=5 */
    for (y=0; y<5; y++)
        n++; /* gets hit five times n=15 */

    /* x=6 */
    for (y=0; y<6; y++)
        n++; /* gets hit six times n=21 */

    /* x=7 */
    for (y=0; y<7; y++)
        n++; /* gets hit seven times n=28 */

    /* x=8 */
    for (y=0; y<8; y++)
        n++; /* gets hit eight times n=36 */

    /* x=9 */
    for (y=0; y<9; y++)
        n++; /* gets hit nine times n=45 */

    /* x=10 exit loop */

    printf ("%d\n", n); /* prints 45 */
}