Saturday, June 6, 2020

Finding whether a number exists as sum of two array elements in an unsorted array

Given the array{2, 10,9,7,8 ,-2}
Find whether sum 8 is possible
As element no.2 (10) and element no.6(-2) are present the sum of the two is 8


Solution: Taking an Sum minus the fixed element, we scan through rest of the array to find another element matching
Complexity: O(n^2)

#include <stdio.h>

int main()
{
    int a[6] = {2, 10,9,7,8 ,-2};
    
    int sum = 8;
    
    int flag = 0;
    int size = sizeof a / sizeof a[0];
    printf("\nSize of array %d", size);
    int i=0;
    int j =0;
    for (i= 0; i<size-1; i++) {
        for(j=i+1; j <size;j++) {
            if(sum-a[i] == a[j]) {
                flag++;
                break;
            }
        }
        if(flag==1) {
            break;
        }
    }
    
    if(flag) {
     printf("\n Element at location(%d):%d and location(%d):%d has sum:%d", i+1,a[i],j+1,a[j],sum);
    }
    else {
        printf("Not found !!");
    }
    return 0;
}

Output:
Size of array 6                                                                                                               
 Element at location(2):10 and location(6):-2 has sum:8

No comments:

Post a Comment