In: Computer Science
Given an unsorted array A of size N of integers, find a continuous sub-array which adds to the given number. Declare dynamic arrays and use only pointers syntax. (no [ ]'s or (ptr+1) stuff.
input will be the number of input values to enter followed by the sum to compare with. print out the continuous sub-array of values that are equal to sum or the message 'no sum ofund.'
there may be more than one sub-array to be found in a given input.
example:
input: 6 10 first number represents 6 values to enter and 10 is the sum
3 5 8 2 3 5 6 input values for the array.
output: 8 2 and 235 these are continuous sub-array values that sum to 10
your input data sets: i would create an input file for the following.
6 10
358235
8 20
5 10 -3 3 10 -3 4 14
6 12
8 5 3 3 7 7
9 15
3 8 4 3 10 2 3 8 2
6 12
8 5 3 3 4 5
20 30
10 12 8 5 15 5 10 8 2 4 6 9 1 7 6 3 2 7 15 18 20 5 3 2 7 9 3 2 1 8 5
#include <iostream> #include <fstream> using namespace std; void printArray(int *data, int i, int j) { for(int x=i; x<=j; x++) { cout << *(data + x) << " "; } cout << endl; } void subArray(int *data, int size, int target) { int currentSum = *data; int startIndex = 0; for(int i=1; i<=size; i++) { while(currentSum > target && startIndex < i-1) { currentSum -= *(data + startIndex); startIndex++; } if(currentSum == target) { printArray(data, startIndex, i-1); return; } if(i < size) { currentSum += *(data + i); } } // if we reach here, it means no solution cout << "no sum found" << endl; } int main() { string fName = "input.txt"; ifstream f(fName.c_str()); if(f.fail()) { cout << "Unable to find file." << endl; return 1; } int size; int target; while(f >> size) { f >> target; int *data = new int[size]; for(int i=0; i<size; i++) { f >> *(data + i); } subArray(data, size, target); } }
************************************************** Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.
Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.
The main { string fName = "input.txt"; main.cpp input.txt ifstream f(fName.c_str(); clang version 7.0.0-3-ubuntu. 18.04.1 (tags/RELEASE_ ? clang++-7 -pthread -o main main.cpp } ./main 8 2 10 -3 3 10 no sum found 3 84 3 4 5 10 12 8 3 2 if(f.fail()) { cout << "Unable to find file." << endl; return 1; int size; int target; while(f >> size) { f > > target; int *data = new int[size]; for(int i=0; i<size; i++) { f » data[i]; subArray(data, size, target);