在while循环内嵌套的do-while循环

时间:2020-09-21 14:15:29

标签: c++ nested-loops

开始学习C ++,遇到任务问题。 该任务要求我将嵌套的for循环重写为while循环内的do-while循环。输出是非常不同的,所以我认为我做错了。 嵌套的for循环:

  #include <stdio.h>

  main()
  {
     int i, j;
     for (i=1; i<=3; i++) {   /* outer loop */
         printf("The start of iteration %d of the outer loop.\n", i);
         for (j=1; j<=4; j++)  /* inner loop */
         printf("Iteration %d of the inner loop.\n", j);
     printf("The end of iteration %d of the outer loop.\n", i);
    }
    return 0;
 }

输出:

The start of iteration 1 of the outer loop.
    Iteration 1 of the inner loop.
    Iteration 2 of the inner loop.
    Iteration 3 of the inner loop.
    Iteration 4 of the inner loop.
The end of iteration 1 of the outer loop.
The start of iteration 2 of the outer loop.
    Iteration 1 of the inner loop.
    Iteration 2 of the inner loop.
    Iteration 3 of the inner loop.
    Iteration 4 of the inner loop.
The end of iteration 2 of the outer loop.
The start of iteration 3 of the outer loop.
    Iteration 1 of the inner loop.
    Iteration 2 of the inner loop.
    Iteration 3 of the inner loop.
    Iteration 4 of the inner loop.
The end of iteration 3 of the outer loop.

我的代码:

#include <stdio.h>

main()
{
    int i, j;
    i = 1;
    j = 1;

    while (i <= 3) {
        printf("The start of iteration %d of the outer loop.\n", i);
        do {
            printf("Iteration %d of the inner loop.\n", j);
            j++;
        } while (j <= 4);
        printf("The end of iteration %d of the outer loop.\n", i);
        i++;
    }
}

输出:

The start of iteration 1 of the outer loop.
Iteration 1 of the inner loop.
Iteration 2 of the inner loop.
Iteration 3 of the inner loop.
Iteration 4 of the inner loop.
The end of iteration 1 of the outer loop.
The start of iteration 2 of the outer loop.
Iteration 5 of the inner loop.
The end of iteration 2 of the outer loop.
The start of iteration 3 of the outer loop.
Iteration 6 of the inner loop.
The end of iteration 3 of the outer loop.

我想念什么吗?

1 个答案:

答案 0 :(得分:1)

您永远不会在第二个设置中将j重置为1。因此,您将其递增得更高,并且内部循环仅运行一次,因为它不满足您的循环条件。

您可以添加如下内容:

while (i <= 3) {
    printf("The start of iteration %d of the outer loop.\n", i);
    j = 1;
    // ^^^
    do {
        printf("Iteration %d of the inner loop.\n", j);
        j++;
    } while (j <= 4);
    printf("The end of iteration %d of the outer loop.\n", i);
    i++;
}