I’ll provide solutions for finding two elements in an array whose sum equals zero in C, C++, Python, and Java.
- Solution in C:
#include <stdio.h> void findElements(int arr[], int n) { for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { if (arr[i] + arr[j] == 0) { printf("Pair found: %d and %dn", arr[i], arr[j]); return; } } } printf("No pair found.n"); } int main() { int arr[] = {2, -5, 7, -3, 1}; int size = sizeof(arr) / sizeof(arr[0]); findElements(arr, size); return 0; }
- Solution in C++:
#include <iostream> #include <unordered_set> void findElements(int arr[], int n) { std::unordered_set<int> elements; for (int i = 0; i < n; i++) { int complement = -arr[i]; if (elements.count(complement)) { std::cout << "Pair found: " << arr[i] << " and " << complement << std::endl; return; } elements.insert(arr[i]); } std::cout << "No pair found." << std::endl; } int main() { int arr[] = {2, -5, 7, -3, 1}; int size = sizeof(arr) / sizeof(arr[0]); findElements(arr, size); return 0; }
- Solution in Python:
def find_elements(arr): elements = set() for num in arr: complement = -num if complement in elements: print("Pair found:", num, "and", complement) return elements.add(num) print("No pair found.") arr = [2, -5, 7, -3, 1] find_elements(arr)
- Solution in Java:
import java.util.HashSet; class Main { static void findElements(int[] arr) { HashSet<Integer> elements = new HashSet<>(); for (int num : arr) { int complement = -num; if (elements.contains(complement)) { System.out.println("Pair found: " + num + " and " + complement); return; } elements.add(num); } System.out.println("No pair found."); } public static void main(String[] args) { int[] arr = {2, -5, 7, -3, 1}; findElements(arr); } }
These solutions iterate over the array and use different techniques to find two elements whose sum is zero. The C and C++ solutions use nested loops and an unordered set, while the Python and Java solutions utilize a set or HashSet to store the elements and check for the existence of the complement.