Logic Building
# Take array
n = int(input("Enter array size: "))
arr = []
for i in range(n):
arr.append(int(input(f"Element {i+1}: ")))
k = int(input("Enter target sum: "))
# Count pairs
count = 0
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] + arr[j] == k:
count += 1
print(f"Number of pairs with sum {k}: {count}")Output
Enter array size: 5 Element 1: 2 Element 2: 4 Element 3: 3 Element 4: 5 Element 5: 1 Enter target sum: 6 Number of pairs with sum 6: 2
Check all pairs using nested loops.
Key Concepts:
- Outer loop: first element
- Inner loop: second element (i+1 to avoid duplicates)
- Count if sum equals k