Header Ads Widget

Find Total Sum | Tech Mahindra coding questions

Find Total Sum:-

Write a program to calculate and return the sum of absolute difference between the adjacent number in an array of positive integers from the position entered by the user.

Note : You are expected to write code in the findTotalSum function only which receive three positional arguments:

1st : number of elements in the array
2nd : array
3rd : position from where the sum is to be calculated

Example

Sample Input
input 1 : 7
input 2 : 11 22 12 24 13 26 14
input 3 : 5

Output
25

Explanation:-

The first parameter 7 is the size of the array. Next is an array of integers and input 5 is the position from where you have to calculate the Total Sum. The output  is 25 as per calculation below. 
| 26-13 | = 13
| 14-26 | =  12
Total Sum = 13 + 12 = 25



Find Total Sum:-

The objective of the code is to write a findtotalsum function which will find the find the sum of absolute difference between the adjacent number in an array of positive integers from the position entered by the user.

C++ code:-

#include<bits/stdc++.h>
using namespace std;

int findTotalSum(int n,int a[],int start)
{
int sum=0;
for(int i=start-1;i<n-1;i++)
{
sum+=abs(a[i+1]-a[i]);
}
return sum;
}


// Driver function
int main()
{
int n,start;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cin>>start;
cout<<findTotalSum(n,a,start);
return 0;
}

Output:-

7
11 22 12 24 13 26 14
5
25

Wipro :-

Infytq :-

Key Points;-

Hackerrank:-


C-tutorial:-

See more:-



Post a Comment

0 Comments