Description: This C++ programing example for Introduction to Computing is a simple C++ code that takes some integers as input in an array. Then, it takes an integer called “sum” as input. Then, the function hasSum searches that sum in the integer array.
#include <iostream>
using namespace std;
bool hasSum(int arr[],int size,int given_sum){
int a=1,b,c,sum;
for(a=1;a<=size;a++){
for (b=0;b<size;b++){
sum=0;
for (c=b;c<a;c++)
sum=sum+arr[c];
if (sum==given_sum)
return true;
}
}
if (sum!=given_sum)
return false;
}
int main()
{
bool answer;
int i=0,sequence[100],input,input_sum,sum=0,lenght;
cout<<"Please enter
a sequence of numbers. To terminate, enter 0"<<endl;
cin>>input;
while (input!=0){
sequence[i]=input;
i++;
cin>>input;
}
lenght=i;
cout<<"Please enter
a sum"<<endl;
cin>>input_sum;
answer=hasSum(sequence,lenght,input_sum);
if (answer==0)
cout<<"Sum was not
found"<<endl;
else
cout<<"Sum was
found"<<endl;
return 0;
}
No comments
Post a Comment