File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed
Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ /* Q. Given an integer array ‘arr[]’ of size n, find sum of all sub-arrays of given array.
2+ Input : a[] = {1, 2, 3}
3+ Output: 20
4+
5+ Explanation: We have to generate all the subarrays using two for loops and then compute their sum.
6+ subarrays --> {1} {12} {123} {2} {23} {3}
7+ subarrays sum --> 1 + 3 + 6 + 2 + 5 + 3 --> 20
8+
9+ Time Complexity: O(n^2)
10+ */
11+
12+ #include < iostream>
13+ using namespace std ;
14+ int main ()
15+ {
16+ int n, sum=0 , result = 0 ;
17+ cin>>n;
18+ int a[n];
19+ for ( int i=0 ; i<n; i++)
20+ {
21+ cin>>a[i];
22+ }
23+
24+ for ( int i=0 ; i<n; i++)
25+ {
26+ sum = 0 ;
27+ for ( int j=i; j<n; j++)
28+ {
29+ sum = sum + a[j];
30+ result = result + sum;
31+ }
32+ }
33+
34+ cout<<" Sum of all Subarrays : " <<result;
35+
36+ return 0 ;
37+ }
You can’t perform that action at this time.
0 commit comments