# Find middle point segment from given segment lengths in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] of size m representing the lengths of line segments.

The line segments are from 0 to arr , arr to arr and so on. Our task is to find the segment which is at the middle of all segments.

Let’s take an example to understand the problem,

## Input

arr[] = {5, 7, 13}

## Output

3

## Explanation

Segments are : (0, 5) , (5, 12), (12, 25)

## Solution Approach

To solve the problem, we will find the middle point of the line by (arrSum/2). If this middle point is a starting or ending point of a line segment then print -1. Else, print the segment number.

Program to illustrate the working of our solution,

## Example

Live Demo

#include <iostream>
using namespace std;
int findSegmentWithMidPoint(int n, int m, int segment_length[]) {
double centerPoint = (1.0 * n) / 2.0;
int sum = 0;
int segment = 0;
for (int i = 0; i < m; i++) {
sum += segment_length[i];
if ((double)sum == centerPoint) {
segment = -1;
break;
}
if (sum > centerPoint) {
segment = i + 1;
break;
}
}
return segment;
}
int main() {
int m = 3;
int segment_length[] = { 5, 7, 13 };
int arrSum = segment_length;
for(int i = 0; i < m; i++)
arrSum += segment_length[i];
int ans = findSegmentWithMidPoint(arrSum, m, segment_length);
cout<<"The segment number where middle point lies is "<<ans;
return 0;
}

## Output

The segment number where middle point lies is 3