LoginSignup
4
2

More than 5 years have passed since last update.

forループで10カウントするごとに処理を実行する

Last updated at Posted at 2017-01-18

1000回カウントするforループで10カウントするごとに処理を実行するプログラムならスラスラと書けるかもしれない。

しかし、ループ0回時も実行することとし、100回ループするごとに1プラスした回数で実行しなければならないとなると少々考え込んでしまう。

まず、考えなければいけないのはループ何回目で処理を実行するかということだ。

上記の要件から以下のカウント数の時に処理を実行することになる。
0,10,20,30.....90,101,111,121.......,979,989,999

考えたのは下のようなモノだが、カウンターを二つ置き、ifの連発なので他に簡単な方法はないものか?と思う。

forループで10カウントするごとに処理実行する

    int countSet = 1000;
    int counter0 = 0;
    int counter1 = 0;

    for (int i = 0; i < countSet; i++) {

        if (counter1 == 10 || i == 0) {//ループ0回目とカウンター10回目で処理を実行する条件文
            cout << i << "-";
            cout << counter1 << endl;//ここで要求された処理の実行
        }

        if (counter1 == 10) {
            counter1 = 0;//10回ごとにカウンター1をリセット
        }

        if (counter0 == 91) {
            counter1 = 0;//ループ91回目でカウンター1をリセット
        }

        if (counter0 == 101) {
            counter0 = 0;//ループ101回目でカウンターゼロをリセット
        }

        counter0++;
        counter1++;
    }
4
2
10

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2