PHP Exercises: Print out the sum of pairs of numbers of a given sorted array of positive integers that is equal to a given number
44. Sum of Number Pairs in Sorted Array
Write a PHP program to print out the sum of pairs of numbers of a given sorted array of positive integers which is equal to a given number.
Sample Solution:
PHP Code:
Explanation:
- Function Definition:
- The function find_Pairs($nums, $pair_sum) is designed to find pairs of numbers in the array $nums that sum up to the specified value $pair_sum.
- Initialize Result Variable:
- A string variable $nums_pairs is initialized to store the pairs of numbers that meet the criteria.
- Outer Loop:
- A for loop iterates through each element in the array $nums using the index variable $i.
- Inner Loop:
- A nested for loop iterates through the subsequent elements of the array starting from the index $i + 1, using the index variable $j.
- Check for Pair Sum:
- Inside the inner loop, an if statement checks if the sum of the elements at indices $i and $j equals the target sum (int)$pair_sum.
- If they do, the pair (in the format "num1,num2;") is concatenated to the $nums_pairs string.
- Return Pairs:
- After checking all possible pairs, the function returns the string containing the pairs that add up to the target sum.
Output:
1,6;2,5;3,4; 0,5;1,4;2,3;
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to identify all unique pairs in a sorted array that sum up to a given target value.
- Write a PHP script to use the two-pointer technique to efficiently find pairs whose sum equals a specified number.
- Write a PHP function to output every pair of numbers from a sorted array that meets a specified summation condition.
- Write a PHP script to compute and display all unique pairs from a sorted array that total a given sum.
Go to:
PREV : Multiply Corresponding List Elements.
NEXT : Sum of Digits.
PHP Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.