By Saravanan.V
In this tutorial, we are going to learn how to find the equilibrium point in the given array in C++.
First, let's consider an array
arr={1,3,5,2,2}
Here the equilibrium element is 5 because arr[0]+arr[1]=4 and arr[3]+arr[4]=4. The approach is to get the total sum of the elements and then initialize a new temp sum to zero. Iterate through the loop by keeping updating temp sum and subtract the total sum by that element. When the total sum and temp sum are equal, that's the equilibrium point.
1.Calculate the total sum of the elements.
2.Initialize the temp sum as 0.
3.Iterate through the loop.
4.Add the element to temp sum.
5.Check the temp sum and total sum are equal, if it is print that element and its position.
6.Subtract the total sum by that element.
#include <bits/stdc++.h> using namespace std; int main() { int n=5,a[n]={1,3,5,2,2},total_sum=0,temp_sum=0,i; if(n==1)//If only one element is present, then 1 is the equilibrium point and that element is equilibrium element cout<<"Equilibrium Point : "<<1<<"\nEquilibrium Element :"<<a[0]<<endl; for(i=0;i<n;i++) total_sum+=a[i]; for(i=0;i<n;i++) { temp_sum=temp_sum+a[i]; if(temp_sum==total_sum) cout<<"Equilibrium Point : "<<i+1<<"\nEquilibrium Element : "<<a[i]<<"\n";
total_sum=total_sum-a[i];
}
}
Equilibrium Point : 3 Equilibrium Element : 5
Submitted by Saravanan.V (Saravanan)
Download packets of source code on Coders Packet
Comments