# Equilibrium index of an array in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

In this problem, we are given an array arr[] consisting of n integer values. Our task is to create a program to find the equilibrium index of an array.

Equilibrium Index is the index at which the sum of all elements before the index is the same as the sum of all elements after the index.

For array arr[] of size n, the equilibrium index is e such that,

sum (arr[0… e-1] ) = sum (arr[e… n-1])

## Let’s take an example to understand the problem,

Input: arr[] = {5, 1, 2, 8, 3, 4, 1}

Output: 3

Explanation:

arr[0] +  arr[1] + arr[2] = arr[4] + arr[5] + arr[6]

=> 5 + 1 + 2 = 3 + 4 + 1

=> 8 = 8

## Solution Approach:

A simple approach would be finding the element by continuously checking weather any element of the array can be an equilibrium number.

For this we will use nested loops. The outer to iterate over the elements of elements of the array. And the inner will be checking whether any element of the array can be made the equilibrium number or not.

## Example

Live Demo

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

int findEquilibriumIndex(int arr[], int n)
{
int prevSum, nextSum;

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

prevSum = 0;
for (int j = 0; j < i; j++)
prevSum += arr[j];
nextSum = 0;
for (int j = i + 1; j < n; j++)
nextSum += arr[j];

if (prevSum == nextSum)
return i;
}
return -1;
}

int main() {

int arr[] = {5, 1, 2, 8, 3, 4, 1};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<"The equilibrium index is "<<findEquilibriumIndex(arr, n);
return 0;
}

## Output −

The equilibrium index is 3
Updated on 22-Jan-2021 12:59:42