C++ Program to find the equilibrium index of an array

Equilibrium index of an array

 

Here,  in this section we will learn about the C++ program to find the equilibrium index of an array. Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes.

Example : Arr[ ] : [-4, 3, 0, 2, -7, 1, 5], in the given array index 3 is an euqilibrium index as  left_sum =  right_sum = -1.   

c++ program to find equilibrium point

Algorithm :

  • Take the size of array from the user, and store it in n.
  • Take the n elements of the array from the user.
  • Initialize left_sum, and find the sum of the elements of array and store it in sum .
  • Iterate from 1 to n-1 and for every i-th index update, left_sum += a[i] and sum -= a[i].
  • Check if left_sum == sum , then that index is the required equilibrium index.

C++ Program based on above algorithm

#include<bits/stdc++.h>
using namespace std;

int main ()
{

int n;

cout << "Enter the size of the array: ";
cin >> n;

int a[n], sum = 0, left_sum = 0;

cout << "\nEnter the elements of the array: ";

for (int i = 0; i < n; i++)
{

cin >> a[i];
sum += a[i];

}

left_sum = a[0];

sum -= a[0];

for (int i = 1; i < n; i++)
{

sum -= a[i];

if (left_sum == sum)
{
cout << "\nEquilibrim index : " << i;
break;
}

left_sum += a[i];
}


return 0;

}
Output :

Enter the size of array : 7

Enter the elements of the array : -4 3 0 2 -7 1 5

Equilibrium index : 3