Before Moving To the problem let us know
what is subarray. ?
Subarray =continuous part of the array
This means we can break it and write once again of the continuous part.
Ex - { 5 , 9 , 2 , 8 , 6 , 1 }
The sub array we can take here is - { 2 , 8 , 6 } This is the continuous part of the sub array.
Number of subarrays of an array with n elements
n^C2+n=n*(n+1)/2
Hope you will get some basic knowledge about Sub array so lets move to the problem
Problem-
Given an array of size n .Output sum of each subarray of the given array
Example-
subarray -
If we start from index 0 = 1 | 1 2 | 1 2 2
If we start from index 1 = 2 |2 2
If we start from index 2 = 2
Logic
- iterate over all the subarrays.
- Use Nested loop
- for every i=0 to i=n
- for every j=i to j=n
- output sum[i..j]
Coding
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n; // This variable is to take the size of array
cout << "Enter the size of array ";
cin >> n;
int arr[n];
for (int i = 0; i < n; i++) {
cout << "Enter the element no." << i + 1 << " :";
cin >> arr[i];
}
int sum = 0;
for (int i = 0; i < n; i++) {
sum = 0; // here we initialize the variable sum =0
for (int j = i; j < n; j++) {
sum = sum + arr[j];
cout << sum << endl; // This for is to print out
// our sum of sub array
}
}
return 0;
}
Output
Ex-1
Enter the size of array 3
Enter the element no.1 : 1
Enter the element no.2 : 2
Enter the element no.3 : 2
1
3
5
2
4
2
Ex-2
Enter the size of array 5
Enter the element no.1 :3
Enter the element no.2 :5
Enter the element no.3 :1
Enter the element no.4 :2
Enter the element no.5 :9
3
8
9
11
20
5
6
8
17
1
3
12
2
11
9
Post a Comment
Post a Comment
Please do not spam in comment