Count of subarrays forming an Arithmetic Progression ( AP ) | C ++ implementation of the above approach ; Function to find the total count of subarrays ; Iterate over each subarray ; Difference between first two terms of subarray ; Iterate over the subarray from i to j ; Check if the difference of all adjacent elements is same ; Driver Code ; Given array ; Function Call
#include <iostream> NEW_LINE using namespace std ; int calcSubarray ( int A [ ] , int N ) { int count = 0 ; for ( int i = 0 ; i < N ; i ++ ) { for ( int j = i + 1 ; j < N ; j ++ ) { bool flag = true ; int comm_diff = A [ i + 1 ] - A [ i ] ; for ( int k = i ; k < j ; k ++ ) { if ( A [ k + 1 ] - A [ k ] == comm_diff ) { continue ; } else { flag = false ; break ; } } if ( flag ) { count ++ ; } } } return count ; } int main ( ) { int A [ 5 ] = { 8 , 7 , 4 , 1 , 0 } ; int N = sizeof ( A ) / sizeof ( int ) ; cout << calcSubarray ( A , N ) ; }