Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

병렬 배열을 구현하는 C++ 프로그램


병렬 배열은 여러 배열을 포함하는 구조입니다. 이러한 각 배열은 크기가 동일하고 배열 요소가 서로 관련되어 있습니다. 병렬 배열의 모든 요소는 공통 개체를 나타냅니다.

병렬 배열의 예는 다음과 같습니다 -

employee_name = { Harry, Sally, Mark, Frank, Judy }
employee_salary = {10000, 5000, 20000, 12000, 5000}

위의 예에서 5명의 다른 직원의 이름과 급여는 2개의 배열에 저장됩니다.

병렬 배열을 보여주는 프로그램은 다음과 같습니다 -

예시

#include <iostream>
#include <string>

using namespace std;
int main() {
   int max = 0, index = 0;
   string empName [ ] = {"Harry", "Sally", "Mark", "Frank", "Judy" };
   string empDept [ ] = {"IT", "Sales", "IT", "HR", "Sales"};
   int empSal[ ] = {10000, 5000, 20000, 12000, 5000 };
   int n = sizeof(empSal)/sizeof(empSal[0]);

   for(int i = 0; i < n; i++) {
      if (empSal[i] > max) {
         max = empSal[i];
         index = i;
      }
   }
   cout << "The highest salary is "<< max <<" and is earned by
   "<<empName[index]<<" belonging to "<<empDept[index]<<" department";
   return 0;
}

출력

위 프로그램의 출력은 다음과 같습니다 -

The highest salary is 20000 and is earned by Mark belonging to IT department

위의 프로그램에서는 사원 이름, 부서 및 급여를 각각 포함하는 세 개의 배열이 선언됩니다. 이것은 다음과 같습니다 -

string empName [ ] = {"Harry", "Sally", "Mark", "Frank", "Judy" };
string empDept [ ] = {"IT", "Sales", "IT", "HR", "Sales"};
int empSal[ ] = {10000, 5000, 20000, 12000, 5000 };

for 루프를 사용하여 가장 높은 급여를 찾고 max에 저장합니다. 가장 높은 급여를 포함하는 인덱스는 인덱스에 저장됩니다. 이것은 아래에 표시됩니다 -

int n = sizeof(empSal)/sizeof(empSal[0]);
for(int i = 0; i < n; i++) {
   if (empSal[i] > max) {
      max = empSal[i];
      index = i;
   }
}

마지막으로 가장 높은 급여와 해당 직원 이름 및 부서가 표시됩니다. 이것은 다음과 같습니다 -

cout << "The highest salary is "<< max <<" and is earned by "<<empName[index]<<"
belonging to "<<empDept[index]<<" department";