C++ Program to Find Manhattan Distance
Introduction
The Manhattan distance, also known as taxicab or L1 distance, measures the absolute difference between coordinates. Unlike the Euclidean distance, it calculates the total distance traveled along axes at right angles, making it particularly useful in grid-based systems such as city maps or in some machine learning algorithms.
This C++ program calculates the Manhattan distance between two points in a 2D plane.
Formula
The Manhattan distance between two points P1(x1, y1)
and P2(x2, y2)
is given by:
Distance = |x2 - x1| + |y2 - y1|
This formula sums the absolute differences of the x-coordinates and y-coordinates. It is conceptually similar to how a taxi would navigate a grid-like street system, moving only along horizontal and vertical streets.
Code
#include <iostream> #include <cmath> using namespace std; int main() { double x1, y1, x2, y2, manhattanDistance; // Input the coordinates of the first point cout << "Enter the x-coordinate of the first point: "; cin >> x1; cout << "Enter the y-coordinate of the first point: "; cin >> y1; // Input the coordinates of the second point cout << "Enter the x-coordinate of the second point: "; cin >> x2; cout << "Enter the y-coordinate of the second point: "; cin >> y2; // Calculate the Manhattan distance manhattanDistance = abs(x2 - x1) + abs(y2 - y1); // Display the result cout << "The Manhattan distance between the two points is: " << manhattanDistance << endl; return 0; }
Output
When you run the program, it will prompt you to enter the coordinates of two points. Based on the input, the program computes and displays the Manhattan distance between these points.
Example:
Enter the x-coordinate of the first point: 1 Enter the y-coordinate of the first point: 2 Enter the x-coordinate of the second point: 4 Enter the y-coordinate of the second point: 6 The Manhattan distance between the two points is: 7
Explanation
The program starts by taking user input for the coordinates of two points in a 2D space. These inputs represent the (x, y)
values of the two points. The Manhattan distance is calculated using the formula:
manhattanDistance = abs(x2 - x1) + abs(y2 - y1);
The abs
function, provided by the cmath
library, ensures that the difference between the coordinates is treated as an absolute value, regardless of which point is larger. For example, with points (1, 2)
and (4, 6)
:
x2 - x1 = 4 - 1 = 3
y2 - y1 = 6 - 2 = 4
manhattanDistance = 3 + 4 = 7
The calculated distance is then printed to the console in a user-friendly message.
Conclusion
This program illustrates how to compute the Manhattan distance between two points in a 2D plane using C++. The Manhattan distance is widely used in various fields, such as grid-based navigation, clustering algorithms, and optimization techniques.