繰り返し処理

forループ

for文:

for (int i = 0; i < 10; i++)
{
  print(i);
}

breakでループを抜ける方法:

int count = 0;
int loopCount = 0;
for (int i = 0; i < 10; i++) {
  count++;
  if(count > 5){
    //countが5になったらループを抜ける
    break;
  }
  loopCount++;
}
print (count);//6
print (loopCount);//5

continueで後続処理をスキップさせる方法:

int count = 0;
int loopCount = 0;
for (int i = 0; i < 10; i++) {
  count++;
  if(count > 5){
    //countが5になったら後続処理をスキップ
    continue;
  }
  loopCount++;
}
print (count);//10
print (loopCount);//5

whileループ

whileループは継続条件が真である間はずっと処理が実行されつづける。 条件が初めから偽の場合には1度も実行されない。 条件式を脱出するように記述しないと無限ループになるので注意が必要。

int count = 4;
while(count > 0)
{
  print (count);
  count--;
}

dowhileループ

dowhileループは、whileループと同様、条件が合致する間は処理が実行されつづけるが、仮に条件式に合致しなくても必ず処理が1度行われる。

int count = 0;
do {
  count--;
  print (count);
} while( count > 0 );

foreachループ

foreachループは中身に複数の要素が格納されている配列などの要素を対象に1つづつ要素を取り出して処理を実行する事ができる。

//ループ用の配列を宣言
string[] array = new string[3];
array[0] = "1番目";
array[1] = "2番目";
array[2] = "3番目";

//foreach文
foreach(string item in array)
{
  print (item);
}