# Write a program to find equilibrium index of an array

27 June 2022

Write a program to find equilibrium index of an array

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

Description

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.

C Program

#include <stdio.h>

int Eqi_Index(int *arr, int n)

{

int i, j;

int l_sum, r_sum;

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

{

l_sum = 0;

for (j = 0; j < i; j++)

{

l_sum += arr[j];

}

r_sum = 0;

for (j = i + 1; j < n; j++)

{

r_sum += arr[j];

}

if (l_sum == r_sum)

{

return i;

}

}

return -1;

}

int main()

{

int n;    scanf("%d",&n);

int arr[n];

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

{

scanf("%d",&arr[i]);

}

printf("%d ",Eqi_Index(arr,n));

return 0;

}

C++ Program

#include <bits/stdc++.h>

using namespace std;

int Eqi_Index(int arr[], int n)

{

int i, j;

int l_sum, r_sum;

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

{

l_sum = 0;

for (j = 0; j < i; j++)

{

l_sum += arr[j];

}

r_sum = 0;

for (j = i + 1; j < n; j++)

{

r_sum += arr[j];

}

if (l_sum == r_sum)

{

return i;

}

}

return -1;

}

int main()

{

int n;    cin>>n;

int arr[n];

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

{

cin>>arr[i];

}

cout<<Eqi_Index(arr,n);

return 0;

}

JAVA Program

import java.util.*;

import java.lang.*;

import java.io.*;

class Main

{

public static int Eqi_Index(int arr[],int n)

{

int i, j;

int l_sum, r_sum;

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

{

l_sum = 0;

for (j = 0; j < i; j++)

{

l_sum += arr[j];

}

r_sum = 0;

for (j = i + 1; j < n; j++)

{

r_sum += arr[j];

}

if (l_sum == r_sum)

{

return i;

}

}

return -1;

}

public static void main (String[] args) throws java.lang.Exception

{

Scanner sc=new Scanner(System.in);

int size = sc.nextInt();

int[] arr = new int[size];

for(int i = 0 ; i<size ; i++)

{

arr[i] = sc.nextInt();

}

System.out.print(Eqi_Index(arr,size));

}

}

PYTHON Program

def Eqi_Index(arr):

l_sum = 0

r_sum = 0

n = len(arr)

for i in range(n):

l_sum = 0

r_sum = 0

for j in range(i):

l_sum += arr[j]

for j in range(i + 1, n):

r_sum += arr[j]

if l_sum == r_sum:

return i

return -1

arr = [10, 2, 4, 12]

print (Eqi_Index(arr))

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023