Search code examples
c++arraysturbo-c++

How to find an element in array such that sum of left array is equal to sum of right array


here is the input and output the code should generate:

  • Input : 1 4 2 5 0
  • Output : 2

Explanation : If 2 is the partition, then: 1+ 4=5(LHS) and 5+0=5(RHS) should print 2, but in my case I'm not getting the output.

I tried my code with the logic that.. the n-th element would be present somewhere in between the array. So considering the sum of element of arr till n-th element will be LHS and from n-th element it would be till the end of the arr which is RHS. Also i added a while loop which increments the pointing element n.

#include <iostream.h>
#include <conio.h>
void main(){
   int arr[5],arr2[5],i,j=0,k=0,n=1;
   cout<<"input_arr\n";
   for(i=0;i<5;i++)
    cin>>arr[i];

   while(n<=5)
{
   for(i=n;i<5;n++)
      j+=arr[i];   //sum of right side arr from n-th   element
   for(i=0;i<n;i++)
    k+=arr2[i];  //sum of left side arr till n-th element
   if(k==j)
    cout<<"\n"<<arr[n];  // prints the equilbrium element
   else
         n++;
}
    getch();
}

Solution

  • First off, you want to reset j, k every iteration with this method, if I understand correctly.

    Second, the second for loop increments n instead of i, for some reason.

    Third, you're also declaring arr2, not initializing it, and adding values in arr2 to k for some reason.

    You're including the median as well. Try n = 2.

    j = arr[2] + arr[3]+arr[4] = 2 + 5 + 0 = 7
    k = arr[0] + arr[1] = 1 + 4 = 0

    proposed changes to while loop (to maintain the same method):

    while (n <= 5) {
        j = 0; k = 0;
        for (i = n+1; i < 5; i++) {
            j+= arr[i];
        }
        for (i = 0; i < n; i++) {
            k+= arr[i]
        }
        if (k == j) {
            cout << "\n" << arr[n];
            break; //you should end the for loop here
        }
        n++;
    }