初心者のためのC


At the end of this lesson, you should be able to answer the following:

  • What is an array?
  • What is an element? What is an index?
  • How do I declare an array in C#?
  • How do I access the values in an array?

これまでのところ、私たちは変数に一つの値を格納していました.しかし、いくつかの状況では、1つ以上の値を格納する変数が必要です.
配列は、同じ型の複数の値を保持するデータ構造体です.これは、型名の末尾にある角括弧で表されます.
int[] scores;
上記では整数の配列を宣言しました.まだ初期化していないので、値はNULLです.
配列を使用するには、まず必要な値を割り当てることで最初に初期化を行う必要があります.この数は配列のサイズを決定します.配列のサイズは固定され、割り当てられると変更できません.
int[] scores = new int[10];
var words = new string[5];
配列を初期化するには、新しいキーワードを使用します.続いて、配列の型と、四角括弧内の値の数を使用します.行2は、我々が学んだVARキーワードを使用して、配列を宣言して、初期化するもう一つの方法を示します.
角括弧を使用して、配列内の値を自分の位置でアクセスできます.各値は要素と呼ばれ、その位置はインデックスです.
いくつかの値を印刷してみましょう.次のコードボックスに入力し、プログラムを実行します.
int[] scores = new int[10];

Console.WriteLine(scores[1]);
配列は初期化されますが、配列の要素はまだdefault values 各タイプの.それでscores[1] プリント0 , のデフォルト値int .
配列の最後の要素にアクセスしてみてください.使用するインデックスを知っていますか?
私たちは10の要素を持っているので、最後の要素は10番目の1つではないだろうか?あなたが下にコードを走ろうとするならば、あなたは驚きを得るかもしれません!
int[] scores = new int[10];

Console.WriteLine(scores[10]);
エラーが起こる10 は最後の要素のインデックスではありません!C≧Cの配列は0から始まるので、インデックスは0 . したがって、10個の要素の配列には0 to 9 .

これをより明確に示すために、まず実際の値を配列に置きましょう.配列宣言中にこれを行うことができます.以下は配列を宣言して初期化するすべての有効な方法です.
int[] arr1 = new int[3] { 10, 20, 30 };
int[] arr2 = new int[] { 10, 20, 30 }; 
int[] arr3 = { 10, 20, 30 }
配列の要素を型の横にあるかっこ括弧内で宣言できます.
1行目と2行目については、int[] 線1と2でvar キーワードと構文は有効です.しかし、3号線と同じことはできません.
2行目と3行目については、配列の大きさは値の数からC≧だけ推論される.
上記のいずれかを使用して宣言するscores いくつかの値を持つ配列.次に、インデックスを持つ要素にアクセスして、最初と最後の要素を出力します0 and 9 それぞれ.
// Declare an array with 10 elements
int[] scores = { 100, 85, 80, 93, 98, 100, 74, 88, 90, 99 };

// Print the first element
Console.WriteLine(scores[0]);

// Print the last element
Console.WriteLine(scores[9]);
プログラムを実行します.最初の要素は100 , 最後の要素は99 .
配列で要素の総数を得ることができますLength プロパティ.上のコードに次のコードを追加し、プログラムを実行します.出力は10 .
Console.WriteLine(scores.Length);

あなたは、我々がどこで使用したか思い出すことができますかLength 前のプロパティ?我々は文字列にはLength 文字列内の文字数を返すプロパティ.偶然の一致?
なぜなら、文字列はchar 値!次の文字列を実行できます.
var move = "consecutive normal punches";
Console.WriteLine($"The 4th character of '{move}' is '{move[3]}'.");

Questions

True or False:

  • Once allocated, the size of an array is fixed and cannot change.
  • You can have both int and string values in an int[] array.
  • The first element of an arrayarr is in arr[0].
  • The last element of an array arr2 is in arr2[arr2.Length-1].
  • This is a valid array declaration: int[] arr3 = new int[];

Challenge

Create a string array with your desired number of elements. Populate it using one of the initialisation expressions shown in the lesson. Then print the first element, last element, and the total number of elements in the array. Use to make the output like this:


First element:
Last element:
Total number of elements:

Challenge

Using the string array in the previous challenge, print out all the elements in the array. (Hint: You can use a !)