How to check if sum of any two elements in sorted array are equal to an input number in C

1 Answer

0 votes
#include <stdio.h> 
 
#define N 10

int sum_numbers_exist(int arr[], int len, int n);
 
int main(void)
{
    int n = 19, arr[N] = { 3, 5, 7, 10, 14, 15, 18, 20, 25, 30 };    
        
    if (sum_numbers_exist(arr, N, n))
        printf("numbers exist");
    else
        printf("numbers not exist");
     
    return 0;
}
 
int sum_numbers_exist(int arr[], int len, int n)
{
    int start = 0, end = len - 1;
    
    while (start < end)
    {
        if (arr[start] + arr[end] == n) return 1;
        if (arr[start] + arr[end] > n) 
            end--;
        else if (arr[start] + arr[end] < n)
                 start++;
    }
    return 0;
}

/* 
run:

numbers exist

*/




answered Sep 26, 2014 by avibootz
...