C++ Program to Implement Parallel Array


A parallel array is a structure that contains multiple arrays. Each of these arrays are of the same size and the array elements are related to each other. All the elements in a parallel array represent a common entity.

An example of parallel arrays is as follows −

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

In the above example, the name and salary of 5 different employees is stored in 2 arrays.

A program that demonstrates parallel arrays is given as follows −

Example

#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;
}

Output

The output of the above program is as follows −

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

In the above program, three arrays are declared, containing the employee name, department and salary respectively. This is given below −

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

The highest salary is found using the for loop and stored in max. The index that contains the highest salary is stored in index. This is shown below −

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

Finally, the highest salary and its corresponding employee name and department are displayed. This is given below −

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

Updated on: 25-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements