Q26. Write a code to find pairs with given sum in an array.
Solution : You are given an array and a number and task is to find all pairs of elements in an integer array whose sum is equal to a given number.
Array :- An array is a collection of data items, all of the same type, accessed using a common name.
For example: int arr[7]={5,8,7,5,6,5,4};
Algorithm for find pairs of elements in an integer array
//Algorithm To Find All Pairs Of Elements In An Integer Array.
START
Step 1 -> Input ARRAY arr[] and NUMBER num.
Step 2 -> for i=0 to length of the arr[]-1:
for j=i+1 to length of the arr[]:
if arr[i]+arr[j] equals to num:
print the output
Loop End
Loop End
STOP
Code for find pairs of elements in an integer array
#include <stdio.h>
int main()
{
int arr[7]={4,3,2,7,5,6,8};
int num=9;
for(int i=0;i<6;i++)
{
for(int j=i+1;j<7;j++)
{
if((arr[i]+arr[j])==num)
{
printf(“%d + %d = %d\n”,arr[i],arr[j],num);
}
}
}
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int arr[7]={4,3,2,7,5,6,8};
int num=9;
for(int i=0;i<6;i++)
{
for(int j=i+1;j<7;j++)
{
if((arr[i]+arr[j])==num)
{
cout<<arr[i]<<” + “<<arr[j]<<” = “<<num<<“\n”;
}
}
}
return 0;
}
public class Main
{
public static void main(String[] args)
{
int arr[] = { 4,3,2,7,5,6,8 };
int num = 9;
for(int i=0;i<6;i++)
{
for(int j=i+1;j<7;j++)
{
if((arr[i]+arr[j])==num)
{
System.out.println(arr[i]+” + “+arr[j]+” = “+num);
}
}
}
}
}
arr = [ 4,3,2,7,5,6,8]
n = len(arr)
num = 9
for i in range(0, n):
for j in range(i+1, n):
if((arr[i]+arr[j])==num):
print(arr[i],” + “,arr[j],” = “,num)
<?php
$arr = array(4,3,2,7,5,6,8);
$num = 9;
for($i=0;$i<6;$i++)
{
for($j=$i+1;$j<7;$j++)
{
if(($arr[$i]+$arr[$j])==$num)
{
echo “$arr[$i] + $arr[$j] = $num\n”;
}
}
}?>
Output
4+5=9
7+2=9
6+3=9
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number