1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【C++】基礎を学ぶ➉~for文~

Last updated at Posted at 2022-07-09

for

繰り返し処理を行うための構文

for文の使い方

for (初期化; 条件式; 更新){
  // 繰り返す処理
}

N回繰り返すときのfor

for (int i = 0; i < N; i++) {
  // 処理
}

break

ループを途中で抜けられる

continue

後の処理を飛ばして次のループへ行ける

for文を使ったプログラム

#include <iostream>

using namespace std;

int main(){
  for (int i = 0; i < 15; i++) {
    if (i % 2 ==0) {
      cout << i << "は偶数" << endl;
    } 
    else {
      cout << i << "は奇数" << endl;
      // 奇数の場合は次のループに行く
      continue;
    }

    cout << i << " / 2 = " << i / 2 << endl;
    
    if (i >= 6) {
      // iが6以上になったときループから抜ける
      cout << "iは6以上です" << endl;
      break;
    }
  }
	return 0;
}
0は偶数
0 / 2 = 0
1は奇数
2は偶数
2 / 2 = 1
3は奇数
4は偶数
4 / 2 = 2
5は奇数
6は偶数
6 / 2 = 3
iは6以上です

次の記事

【C++】基礎を学ぶ⑪~while文~

1
0
0

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?