1
1

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 5 years have passed since last update.

C#の基本文法 - 配列

Posted at

授業でした内容を自分のメモとして書き残します。


C#の基本文法 - 配列


配列とは?

〇 多くの値をひとまとめに扱える変数
⇒ 大量のデータを処理するような時に使う

1. 基本操作

〇 「宣言」「作成」「リテラル」「値の取得・変更」について

基本操作
//宣言
タイプ[] 変数;

//作成
変数 = new タイプ [ 整数 ];

//リテラル
{ 1, 2, ……};

//値の取得・変更
変数 = 配列[ 番号 ];
配列[ 番号 ] = ;

■ 番号(インデックス)
⇒ 10個の保管場所を作った場合、用意されるインデックス番号は「0~9」である
※ 「1~10」ではない!

2. 配列のプログラムの例

ex
static void Main(string[] args)
{
    int[] data = { 98, 76, 59, 87, 65};
    int total = 0;

    for ( int i = 0; i < 5; i++ )
    {
        total += data[i];
    }
    Console.WriteLine("合計" + total);
    Console.WriteLine("平均" + (total / 5));

    Console.ReadKey();
}

実行結果
1.png

■ マジックナンバー
⇒ プログラムのソースコード中に書かれた具体的な数値
「 for ( int i = 0; i < 5; i++ ) 」
の中の「5」のような数字を指す

・当初は定義した数値の意図を把握しているが、後にソースコードを見返した(メンテナンス)時など意図を忘れた時に見ると、なぜかわからないがプログラムは動いている、魔法の数字だ、と言われる

■ Length
前述した「5」のような数字が後に「10」などに変わることがあれば、プログラム中のそのすべてを修正する必要がある

⇒ 要素数を調べる

Length.ex
static void Main(string[] args)
{
    int[] data = { 98, 76, 59, 87, 65, 48, 83, 59, 37, 82, 61};
    int total = 0;

    for ( int i = 0; i < data.Length; i++ )
    {
        total += data[i];
    }
    Console.WriteLine("合計" + total);
    Console.WriteLine("平均" + (total / data.Length));

    Console.ReadKey();
}

実行結果
2.png

3. foreach

〇 すべての要素を変数に取り出して処理を実行し終えたら、自動的に構文を抜ける

ex
foreach( タイプ 変数 in 配列 )
{
        ……繰り返す処理……
}
foreach.ex
static void Main(string[] args)
{
    int[] data = { 98, 76, 59, 87, 65, 48, 83, 59, 37, 82, 61};
    int total = 0;

    foreach ( int i in data )
    {
        total += i;
    }
    Console.WriteLine("合計" + total);
    Console.WriteLine("平均" + (total / data.Length));

    Console.ReadKey();
}

配列dataから順に値が取り出され、変数iに収められていく

4. 配列の問題点

〇 大きな問題点は次の二つ

  1. 同じタイプの値しか入れられない
  • 配列とは、同じタイプの値を整理するというものであり、他のタイプのものは入れられない
  1. 要素の増減ができない
  • 要素数は最初の作成時に決まるもので、後での増減は不可である

最後までお読みいただきありがとうございました。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?