gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)
Write a program in C to find a pair with given sum in the array
- User
Write a program in C to find a pair with given sum in the array
- Assistant
Here is a program in C to find a pair with a given sum in an array:
#include <stdio.h> void findPair(int arr[], int n, int sum) { // Initializing variables int i, j; int flag = 0; // Checking each element except the last one for (i = 0; i < n-1; i++) { // Checking each element after the ith element for (j = i+1; j < n; j++) { // If the pair with the given sum is found, print it if (arr[i] + arr[j] == sum) { printf("Pair found at index %d and %d (%d + %d)\n", i, j, arr[i], arr[j]); flag = 1; } } } // If no pair with the given sum is found, print a message if (!flag) printf("No pair with sum %d is found.\n", sum); } int main() { int arr[] = {1, 5, 9, 2, 3, 7, 4}; int n = sizeof(arr)/sizeof(arr[0]); int sum = 10; findPair(arr, n, sum); return 0; }In this program, we have a function
findPairthat takes an arrayarr, its sizen, and the desired sum as parameters. We iterate through each element in the array except the last one and check it with the elements that come after it. If a pair with the given sum is found, we print the indices and the elements that form the pair.In the main function, we initialize the array
arr, its sizen, and the desired sumsum. We call thefindPairfunction with these parameters to find the pairs with the given sum in the array.