Click here to Skip to main content
15,886,006 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C++
#include <stdio.h>
#include <stdlib.h>

//program to find pair with given sum in the array.
void findPair(int arr[], int n, int sum)
{
    int i,j;
    for(i=0;i<n-1;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(arr[i] + arr[j] == sum)
            {
                printf("Pair found at index %d and %d", i,j);
                return;
            }
        }
    }
    printf("Pair not found");
}
int main()
{
    int arr[] = { 8,7,2,5,3,1};
    int sum = 10;

    int n = sizeof(arr)/sizeof(arr[0]);
    findPair(arr, n, sum);
    return 0;
}


What I have tried:

C++
#include <stdio.h>
#include <stdlib.h>

//program to find pair with given sum in the array.
void findPair(int arr[], int n, int sum)
{
    int i,j;
    for(i=0;i<n-1;i++)
    {
        for(j=i+1;j<n;j++)
        {
            if(arr[i] + arr[j] == sum)
            {
                printf("Pair found at index %d and %d", i,j);
                return;
            }
        }
    }
    printf("Pair not found");
}
int main()
{
    int arr[] = { 8,7,2,5,3,1};
    int sum = 10;

    int n = sizeof(arr)/sizeof(arr[0]);
    findPair(arr, n, sum);
    return 0;
}
Posted
Updated 24-Nov-17 20:41pm
v2
Comments
Kenneth Haugland 25-Nov-17 2:06am    
Why do you send n to your function? Your calculation of it also looks strange to me.

1 solution

It's the number of elements in your array:
C++
int arr[] = { 8,7,2,5,3,1};
... 
int n = sizeof(arr)/sizeof(arr[0]);

sizeof(arr) is the total number of bytes in the array, sizeof(arr[0]) is the size in bytes of the first element of the array, so n is bytes in array / bytes in each element == elements in array.
 
Share this answer
 
Comments
CPallini 25-Nov-17 6:42am    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900