すべてを記述するプログラムから,for文を使ったプログラムへの進化

1.目的

以下のような表示をさせたい。

(0) A child says, "The king is naked."
(1) A child says, "The king is naked."
(2) A child says, "The king is naked."
(3) A child says, "The king is naked."
(4) A child says, "The king is naked."

2.すべてを記述するプログラム
最初は,すべてを記述するプログラムを作成してみる。

#include <stdio.h>

int main()
{
    printf("(0) ");
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    printf("(1) ");
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    printf("(2) ");
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    printf("(3) ");
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    printf("(4) ");
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    return 0;
}

3.値が変わるところを,数値表示のプログラムにする

#include <stdio.h>

int main()
{
    printf("(%d) ",0);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    printf("(%d) ",1);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    printf("(%d) ",2);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    printf("(%d) ",3);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    printf("(%d) ",4);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    return 0;
}

4.できるだけ,同じことを何回も書く形式に変更する
同じことを何回も書く形式のプログラムにすると,for文を使う道筋が見える。
値を直接表示するのではなく,変数iを用いると,同じ形が見えてくる。
プログラム中 i++; というのは i=i+1; と同じ意味で,iの値を1増やせの意味となる。

include <stdio.h>

int main()
{
    int i;
    i=0;
   
    printf("(%d) ",i);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    i++;
   
    printf("(%d) ",i);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    i++;
   
    printf("(%d) ",i);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    i++;
   
    printf("(%d) ",i);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    i++;
   
    printf("(%d) ",i);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    i++; /*この部分は無意味*/
   
    return 0;
}

このプログラムでは,つぎの形が何回も使われている

    printf("(%d) ",i);
    printf("A child says, ");
    printf("\"The king is naked.\"\n");
    i++;

5.ここでfor文を導入する

#include <stdio.h>

int main()
{
    int i;
    for (i=0; i<5; i++) {
        printf("(%d) ",i);
        printf("A child says, ");
        printf("\"The king is naked.\"\n");
    }
    return 0;
}