text: Sum of all Subarrays | Set 1 | Efficient C ++ program to compute sum of subarray elements ; function compute sum all sub - array ; computing sum of subarray using formula ; return all subarray sum ; driver program to test above function
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; long int SubArraySum ( int arr [ ] , int n ) { long int result = 0 ; for ( int i = 0 ; i < n ; i ++ ) result += ( arr [ i ] * ( i + 1 ) * ( n - i ) ) ; return result ; } int main ( ) { int arr [ ] = { 1 , 2 , 3 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << " Sum ▁ of ▁ SubArray ▁ : ▁ " << SubArraySum ( arr , n ) << endl ; return 0 ; }