Program to find a sub array which adds up to a given value
This program finds a sub-array from a given unsorted array which adds up to sum a given value.
here,
T is number of test cases,
N is size of array,
S is given sum value and
array is the given array.
Program:
#include <iostream>
using namespace std;
int main() {
int T, N, S, sum=0, value=0, ivalue, jvalue;
cout<<"Enter number of test cases: ";
cin>>T;
if(T<1)
{
cout<<"Invalid entry of number of test cases";
}
for(int i=0; i<T; i++)
{
cout<<"\n********* Test "<<i+1<<" **********"<<endl;
cout<<"Enter the size of array: ";
do
{
cin>>N;
if(N>200)
{
cout<<"Size cannot be greater than 200";
}
}while(N>200);
cout<<"Enter the sum: ";
cin>>S;
int array[N];
cout<<"Enter array elements: ";
for(int i=0; i<N; i++)
{
cin>>array[i];
}
for(int i=0; i<N; i++)
{
sum = 0;
value = array[i];
for(int j=i+1; j<N; j++)
{
sum = sum + value + array[j];
value=0;
if(S == sum)
{
ivalue = i+1;
jvalue = j+1;
break;
}
}
if(S==sum)
{
cout<<"Position: "<<ivalue<<" to "<<jvalue<<" is "<<sum<<endl;
break;
}
}
} //for loop of Test cases ending
return 0;
}
Output:
here,
T is number of test cases,
N is size of array,
S is given sum value and
array is the given array.
Program:
#include <iostream>
using namespace std;
int main() {
int T, N, S, sum=0, value=0, ivalue, jvalue;
cout<<"Enter number of test cases: ";
cin>>T;
if(T<1)
{
cout<<"Invalid entry of number of test cases";
}
for(int i=0; i<T; i++)
{
cout<<"\n********* Test "<<i+1<<" **********"<<endl;
cout<<"Enter the size of array: ";
do
{
cin>>N;
if(N>200)
{
cout<<"Size cannot be greater than 200";
}
}while(N>200);
cout<<"Enter the sum: ";
cin>>S;
int array[N];
cout<<"Enter array elements: ";
for(int i=0; i<N; i++)
{
cin>>array[i];
}
for(int i=0; i<N; i++)
{
sum = 0;
value = array[i];
for(int j=i+1; j<N; j++)
{
sum = sum + value + array[j];
value=0;
if(S == sum)
{
ivalue = i+1;
jvalue = j+1;
break;
}
}
if(S==sum)
{
cout<<"Position: "<<ivalue<<" to "<<jvalue<<" is "<<sum<<endl;
break;
}
}
} //for loop of Test cases ending
return 0;
}
Output:
Comments
Post a Comment