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

【C#】繰り返し処理と活用例

Posted at

はじめに

C#のスキルチェックで新たに学んだことを紹介する記事です。
記事の内容に誤りがあるかもしれませんが、ご了承ください。
(誤りがありましたら修正いたします:bow_tone1:

基本的な繰り返し処理

同じ処理を指定回数処理したい時に使用するのが、繰り返し(ループ)処理です。

Loop.cs
// for文
// 指定回数ループする
for(int i = 0; i < 3; i++)
{
    Console.Write(i); // 出力結果:012
}

// while文
// 条件が満たされている間ループする
int n = 3;
while(n > 0)
{
    Console.Write(n); // 出力結果:321
    n--;
}

// do-while文
// ループ後に条件判定する
int n = 0;
do
{
    Console.Write(n); // 出力結果:0(必ず1回は実行される)
    n--;
}while(n > 0);

// foreach文
// 全ての要素を参照する
int[] n = {10, 15, 20};
foreach(int val in n)
{
    Console.Write(val); // 出力結果:101520
}

より詳細を知りたい方はこちらをご確認ください。

繰り返し処理を活用した複雑なコード

自然数 X, Y を入力し、要素数 X で自然数からなる数列 A 、要素数 Y で自然数からなる数列 B を入力します。
数列 A の値を B_1 個、B_2個、... B_X 個で分割し、それぞれの数列を改行区切りで出力するコードを考えてみます。

Output.cs
// 期待する出力結果
1 2 3
4 5 6 7
8
9
Sample.cs
using System;

class Program
{
    static void Main()
    {
        int X = 9;
        int Y = 4;
        int[] A = {1, 2, 3, 4, 5, 6, 7, 8, 9};
        int[] B = {3, 4, 1, 1};
        int begin = 0; // 1行で出力する最初の値のインデックス
        // 二重ループ
        for(int i = 0; i < Y; i++)
        {
            int end = begin + B[i] - 1; // 終点の設定、1行で出力する最後の値のインデックス
            for(int j = begin; j <= end; j++)
            {
                Console.Write(A[j]);
                if(j < end)
                {
                    Console.Write(" ");
                }
                else
                {
                    Console.WriteLine();
                }
            }
            begin = end + 1; // 始点の更新、i番目に出力する数列の始点はi-1番目に出力する数列の終点+1
        }
    }
}

指定回数の処理を繰り返す for 文に加えて、終点(改行)の設定、改行先の始点を指定するコードです。
二重ループを活用し、指定のタイミングで改行することができますが、このコードでは始点・終点をどのように設定するかがポイントになると思います。

まとめ

ここでは、基本的な繰り返し処理と活用例を紹介しました。
forループの中にさらにforループを記述する二重ループを活用すれば九九表や罫線入りの表が作成でき、始点・終点の設定をすればより複雑な表も作成できます。

C#でプログラミングの基礎を学んだつもりでしたが、アルゴリズム問題等を通じて新しく学ぶことがあるので、引き続きアウトプットしていきたいと思います。

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