how to calculate sum of two arrays code example

Example 1: Write a program to find the sum of all sub-arrays of a given integer array.

long int SubArraySum( int arr[] , int n ) 
{ 
    long int result = 0; 
  
    // computing sum of subarray using formula 
    for (int i=0; i

Example 2: Write a C program to add negative values among N values using 2D array and pointer

1 Write a program to add negative values among N values using 2D array and pointer

Example 3: sum of arrays

/**
 * C program to find sum of all elements of array 
 */

#include 
#define MAX_SIZE 100

int main()
{
    int arr[MAX_SIZE];
    int i, n, sum=0;

    /* Input size of the array */
    printf("Enter size of the array: ");
    scanf("%d", &n);

    /* Input elements in array */
    printf("Enter %d elements in the array: ", n);
    for(i=0; i

Example 4: find pair in unsorted array which gives sum x

// C++ program to check if given array 
// has 2 elements whose sum is equal 
// to the given value 
  
#include  
using namespace std; 
  
// Function to check if array has 2 elements 
// whose sum is equal to the given value 
bool hasArrayTwoCandidates(int A[], int arr_size, 
                           int sum) 
{ 
    int l, r; 
  
    /* Sort the elements */
    sort(A, A + arr_size); 
  
    /* Now look for the two candidates in  
       the sorted array*/
    l = 0; 
    r = arr_size - 1; 
    while (l < r) { 
        if (A[l] + A[r] == sum) 
            return 1; 
        else if (A[l] + A[r] < sum) 
            l++; 
        else // A[i] + A[j] > sum 
            r--; 
    } 
    return 0; 
} 
  
/* Driver program to test above function */
int main() 
{ 
    int A[] = { 1, 4, 45, 6, 10, -8 }; 
    int n = 16; 
    int arr_size = sizeof(A) / sizeof(A[0]); 
  
    // Function calling 
    if (hasArrayTwoCandidates(A, arr_size, n)) 
        cout << "Array has two elements with given sum"; 
    else
        cout << "Array doesn't have two elements with given sum"; 
  
    return 0; 
}

Tags: