산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C# 배열

C# 배열

이 자습서에서는 C# 배열에 대해 배웁니다. 예제를 통해 배열을 생성, 초기화 및 액세스하는 방법을 배웁니다.

배열은 유사한 유형의 데이터 모음입니다. 예를 들어,

5명의 학생의 나이를 기록해야 한다고 가정합니다. 5개의 개별 변수를 만드는 대신 단순히 배열을 만들 수 있습니다.

<그림> <시간>

1. C# 배열 선언

C#에서 배열을 선언하는 방법은 다음과 같습니다.

datatype[] arrayName;

여기,

예를 들어 보겠습니다.

int[] age;

여기에서 age라는 배열을 만들었습니다. . int의 요소를 저장할 수 있습니다. 유형.

하지만 얼마나 많은 요소를 저장할 수 있나요?

배열이 보유할 수 있는 요소의 수를 정의하려면 C#에서 배열에 대한 메모리를 할당해야 합니다. 예를 들어,

// declare an array
int[] age;

// allocate memory for array
age = new int[5];

여기, new int[5] 배열이 5개의 요소를 저장할 수 있음을 나타냅니다. 배열의 크기/길이가 5라고 말할 수도 있습니다.

참고 :배열의 메모리를 한 줄로 선언하고 할당할 수도 있습니다. 예를 들어,

int[] age = new int[5];
<시간>

2. C#에서 배열 초기화

C#에서는 선언 중에 배열을 초기화할 수 있습니다. 예를 들어,

int [] numbers = {1, 2, 3, 4, 5};

여기에서는 숫자라는 이름의 배열을 만들고 1 값으로 초기화했습니다. , 2 , 3 , 4 , 및 5 중괄호 안에.

배열의 크기는 제공하지 않았습니다. 이 경우 C#은 배열의 요소 수(예:5)를 계산하여 크기를 자동으로 지정합니다.

배열에서는 색인 번호를 사용합니다. 각 배열 요소의 위치를 ​​결정합니다. 인덱스 번호를 사용하여 C#에서 배열을 초기화할 수 있습니다. 예를 들어,

// declare an array
int[] age = new int[5];

//initializing array
age[0] = 12;
age[1] = 4;
age[2] = 5;
...
<그림>

참고 :

<시간>

3. 배열 요소 액세스

배열의 인덱스를 사용하여 배열의 요소에 액세스할 수 있습니다. 예를 들어,

// access element at index 2
array[2];

// access element at index 4
array[4];

여기,

<시간>

예:C# 배열

using System;

namespace AccessArray {
  class Program  {
    static void Main(string[] args) {

      // create an array
      int[] numbers = {1, 2, 3};

      //access first element
      Console.WriteLine("Element in first index : " + numbers[0]);

      //access second element
      Console.WriteLine("Element in second index : " + numbers[1]);

      //access third element
      Console.WriteLine("Element in third index : " + numbers[2]);

      Console.ReadLine();

    }
  }
}

출력

Element in first index : 1
Element in second index : 2
Element in third index : 3

위의 예에서 numbers라는 배열을 만들었습니다. 1, 2, 3 요소 포함 . 여기에서는 색인 번호를 사용하고 있습니다. 배열의 요소에 액세스합니다.

<시간>

4. 배열 요소 변경

배열의 요소를 변경할 수도 있습니다. 요소를 변경하려면 해당 특정 인덱스에 새 값을 할당하기만 하면 됩니다. 예를 들어,

using System;

namespace ChangeArray {
  class Program {
    static void Main(string[] args) {

      // create an array
      int[] numbers = {1, 2, 3};

      Console.WriteLine("Old Value at index 0: " + numbers[0]);

      // change the value at index 0
      numbers[0] = 11;

      //print new value
      Console.WriteLine("New Value at index 0: " + numbers[0]);

      Console.ReadLine();
    }
  }
}

출력

Old Value at index 0: 1
New Value at index 0: 11

위의 예에서 인덱스 0의 초기 값은 1입니다. 행에 주목하십시오.

//change the value at index 0
numbers[0] = 11;

여기에서 11이라는 새 값을 할당합니다. 이제 인덱스 0의 값이 1에서 변경됩니다. 11까지 .

<시간>

5. 루프를 사용하여 C# 배열 반복

C#에서는 루프를 사용하여 배열의 각 요소를 반복할 수 있습니다. 예를 들어,

예:for 루프 사용

using System;

namespace AccessArrayFor {
  class Program {
    static void Main(string[] args) {

      int[] numbers = { 1, 2, 3};
 	 
      for(int i=0; i < numbers.Length; i++) {
        Console.WriteLine("Element in index " + i + ": " + numbers[i]);
      }

      Console.ReadLine();
    }
  }
}

출력

Element in index 0: 1
Element in index 1: 2
Element in index 2: 3

위의 예에서는 for 루프를 사용하여 numbers 배열의 요소를 반복했습니다. . 줄을 주목하십시오.

numbers.Length

여기서 Length 배열의 속성은 배열의 크기를 제공합니다.

foreach 루프를 사용하여 배열의 요소를 반복할 수도 있습니다. 예를 들어,

예:foreach 루프 사용

using System;

namespace AccessArrayForeach {
  class Program {
    static void Main(string[] args) {
      int[] numbers = {1, 2, 3};

      Console.WriteLine("Array Elements: ");

      foreach(int num in numbers) {
        Console.WriteLine(num);
      }

      Console.ReadLine();
    }
  }
}

출력

Array Elements:
1
2
3
<시간>

6. System.Linq를 사용한 C# 배열 작업

C#에는 System.Linq가 있습니다. 배열에서 다양한 작업을 수행하기 위해 다양한 메서드를 제공하는 네임스페이스입니다. 예를 들어,

예:최소 및 최대 요소 찾기

using System;

 // provides us various methods to use in an array
using System.Linq;

namespace ArrayMinMax {
  class Program  {
    static void Main(string[] args) {

      int[] numbers = {51, 1, 3, 4, 98};

      // get the minimum element
      Console.WriteLine("Smallest  Element: " + numbers.Min());  

      // Max() returns the largest number in array
      Console.WriteLine("Largest Element: " + numbers.Max());  
 	 
      Console.ReadLine();
    }
  }
}

출력

Smallest Element: 1
Largest Element: 98

위의 예에서

예:배열의 평균 찾기

using System;
// provides us various methods to use in an array
using System.Linq;

namespace ArrayFunction {
  class Program  {
    static void Main(string[] args) {

      int[] numbers = {30, 31, 94, 86, 55};
 	 
      // get the sum of all array elements
      float sum = numbers.Sum();
 	 
      // get the total number of elements present in the array
      int count = numbers.Count();
 	 
      float average = sum/count;

      Console.WriteLine("Average : " + average);
 	
      // compute the average
      Console.WriteLine("Average using Average() : " + numbers.Average());
 	 
      Console.ReadLine();
    }
  }
}

출력

Average : 59.2
Average using Average() : 59.2

위의 예에서는

를 사용했습니다.

그런 다음 합계를 개수로 나누어 평균을 구합니다.

float average = sum / count;

여기에서는 numbers.Average()도 사용했습니다. System.Linq 메소드 평균을 직접 구하려면 네임스페이스를 사용하세요.

참고 :System.Linq은 필수 사용 Min()를 사용하는 동안 네임스페이스 , Max() , Sum() , Count()Average() 방법.


C 언어

  1. C# 들쭉날쭉한 배열
  2. C++ 프로그래밍에서 함수에 배열 전달
  3. C의 함수에 배열 전달
  4. 배열과 포인터의 관계
  5. 자바 복사 배열
  6. C++의 배열 | 선언 | 초기화 | 배열 예제에 대한 포인터
  7. 예제를 사용한 C++ 배열 동적 할당
  8. Java Arrays Tutorial:선언, 생성, 초기화 [예시]
  9. MATLAB - 배열
  10. 볼 그리드 어레이에 대한 궁극적인 가이드