write a simple basic program(not comples) using C/C++, define an integer array (
ID: 3890331 • Letter: W
Question
write a simple basic program(not comples) using C/C++, define an integer array (size between 10 and 20) and a target number (e.g. 50), assign the array with random numbers in between [0, 10]), then define a function to find all unique number pairs or tuples (more than 2 numbers) of the array such that the numbers of each pair/tuple add up to the target number. Note that besides printing the numbers of each pair/tuple, you are also required to print the original index information of the numbers. For example, given array A = {5, 3, 4, 2, 6, 7}, target = 9, the number pairs are (5, 4), (3, 6), (2, 7), and (3, 4, 2). Their indices are (0, 2), (1, 4), (3, 5), and (1, 2, 3), respectively.Explaining how it works would be appreciated
Explanation / Answer
#include<iostream>
#include <cstdlib>
using namespace std;
//function to find pairs
void findPairs(int arr[],int target){
cout<<" Finding pairs on random array : ";
for(int i=0;i<sizeof(arr);i++){
cout<<arr[i]<<",";
}
cout<<" to get target sum : "<<target;
for(int i=0;i<sizeof(arr);i++){
for(int j=i+1;j<sizeof(arr);j++){
if((arr[i]+arr[j])==target){
cout<<" Pair : ("<<arr[i]<<","<<arr[j]<<")"<<"|| Indices : ("<<i<<","<<j<<")";
}
for(int k=j+1;k<sizeof(arr);k++){
if((arr[i]+arr[j]+arr[k])==target){
cout<<" Pair : ("<<arr[i]<<","<<arr[j]<<","<<arr[k]<<")"<<"|| Indices : ("<<i<<","<<j<<","<<k<<")";
}
}
}
}
}
int main(){
int arr[10];
int target;
// get target sum value
cout<<"Enter Target Sum : ";
cin>>target;
//generate 10 random integers
for(int i=0;i<10;i++){
arr[i] = (rand()%10) +1;
}
findPairs(arr,target);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.