Check for a pair in array which is equal to sum | Infosys
Given an array a[] of n numbers and another number num, check for a pair whether or not there exist two elements in a[] whose sum is exactly num.
Logic:
- Get the array elements and num value from the user.
- Arrange the elements in ascending order.
- Initialize l as 0 and r as arr_size-1.
- Then check three conditions to find numbers.
- If Sum of a[l] and a[r] is equal to num than numbers are found.
- And Sum of a[l] and a[r] is lesser than num then increments l.
- The Sum of a[l] and a[r] is greater than num then decrements r.
- The process continues until l < r.
Explanation:
- Let us consider input n=7 and a[]={2,3,1,5,4}
- First of all, arrange the array elements in ascending order {1,2,3,4,5} and assign the l=0 and r=sizeofarray – 1 ie,4
- Then add a[l] & a[r] and compare with n, now a[0]=1 and a[4]=5 its sum is 6 and less than n then increment l=1
- Now compare the sum of a[1]=2 & a[4]=5 is 7 is equal to n and print the elements and decrement r=3
- Now compare the sum of a[1]=2 & a[3]=4 is 6 is less than n and increment l=2
- Then compare the elements in a[2]=3 & a[3]=5 sum is 7 and sum is equal to n then print the elements and decrement r=3
- Now both l and r are equal and break from the while loop.
Check for a pair in the array which is equal to the sum:
Program:
#include<stdio.h> void main() { int a[20],num,n,i,j,l,r,temp; printf("enter the size of array:"); scanf("%d",&n); printf("enter the elements:"); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("Enter the number to find:"); scanf("%d",&num); l=0,r=n-1; //initialize the left and right elements for(i=0;i<n;i++) //sort the elements in ascending order { for(j=i+1;j<n;j++) { if(a[i]>a[j]) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } } while(l<r) { if(a[l]+a[r]==num) //prints the numbers when it's found { i=0; printf("Numbers are %d and %d",a[l],a[r]); r--; } else if(a[l]+a[r]<num) //increments the l when num is large { l++; } else //decrements the r when num is small { r--; } } if(i!=0) //print when no elements found { printf("Numbers not found"); } }