This blog is under construction

Sunday, 28 July 2013

C program to calculate the balance index of the given array

Write a C program to find the balance point in an array.
Consider the below array
{ 10, 20, 30, 18, 12}

Find the sum from left to right.
{10, 10 + 20, 10 + 20 + 30, 10 + 20 + 30 + 18, 10 + 20 + 30 + 18 + 12}
{10, 30, 60, 78, 90}

Find the sum from right to left.
10 + 20 + 30 + 18 + 12, 20 + 30 + 18 + 12, 30 + 18 + 12, 18 + 12, 12}
{90, 80, 60, 30, 12}


Sum(Left to Right) : {10, 30, 60, 78, 90}
Sum(Right to Left) : {90, 80, 60, 30, 12}

Here, index 2 has same value in both the sum arrays.  Value corresponds to index 2 in input array is 30.  So, 30 is the balance point for the given array.



  #include <stdio.h>
  #define MAX 256

  int main() {
        int arr[MAX], leftToRight[MAX], rightToLeft[MAX];
        int sum, i, j, n;

        /* get the number of entries from the user */
        printf("Enter the number of entries:");
        scanf("%d", &n);

        /* get the array entries from the user */
        printf("Enter your array entries:\n");
        for (i = 0; i < n; i++) {
                printf("Data[%d]: ", i);
                scanf("%d", &arr[i]);
        }

        /* find the left to right sum */
        for (i = 0; i < n; i++) {
                sum = 0;
                for (j = 0; j <= i; j++) {
                        sum = sum + arr[j];
                }
                leftToRight[i] = sum;
        }

        /* find right to left sum */
        for (i = 0; i < n; i++) {
                sum = 0;
                for (j = i; j <= n - 1; j++) {
                        sum = sum + arr[j];
                }
                rightToLeft[i] = sum;
        }

        /* print left to right sum  values */
        printf("Sum from left to right:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", leftToRight[i]);
        }
        printf("\n");

        /* print right to left sum values */
        printf("Sum from right to left:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", rightToLeft[i]);
        }
        printf("\n");

        /* checking for balance point */
        for (i = 0; i < n; i++) {
                if (leftToRight[i] == rightToLeft[i]) {
                        break;
                }
        }

        /* printing the result */
        if (i == n) {
                printf("No balance point in the given matrix!!\n");
        } else {
                printf("%d is the balance point of the given matrix!!\n", arr[i]);
        }

        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the number of entries:5
  Enter your array entries:
  Data[0]: 10
  Data[1]: 20
  Data[2]: 30
  Data[3]: 18
  Data[4]: 12

  Sum from left to right:
  10 30 60 78 90 
  Sum from right to left:
  90 80 60 30 12 

  30 is the balance point of the given matrix!!


No comments:

Post a Comment