C Program to Find Manhattan Distance
Introduction
The Manhattan distance, also known as the "taxicab distance" or "L1 norm," measures the total absolute difference between the corresponding coordinates of two points. This distance metric assumes movement along grid lines, much like navigating city streets where you can only move in horizontal or vertical directions.
It is widely used in fields like machine learning, robotics, and network routing, where the concept of straight-line (Euclidean) distance is not applicable or practical.
In this article, we will write a simple C program to calculate the Manhattan distance between two points in a 2D space, with step-by-step guidance.
Formula
The Manhattan distance between two points, (x1, y1)
and (x2, y2)
, in a 2D space is calculated using the formula:
distance = |x2 - x1| + |y2 - y1|
Here, |x2 - x1|
represents the absolute difference between the x-coordinates, and |y2 - y1|
represents the absolute difference between the y-coordinates.
Steps to calculate:
- Find the absolute difference between the x-coordinates:
|x2 - x1|
. - Find the absolute difference between the y-coordinates:
|y2 - y1|
. - Add the two absolute differences to get the Manhattan distance.
Code
The following is the C program to compute the Manhattan distance:
#include <stdio.h> #include <stdlib.h> // For abs() int main() { int x1, y1, x2, y2, distance; // Input coordinates of the first point printf("Enter x1 and y1: "); scanf("%d %d", &x1, &y1); // Input coordinates of the second point printf("Enter x2 and y2: "); scanf("%d %d", &x2, &y2); // Calculate Manhattan distance distance = abs(x2 - x1) + abs(y2 - y1); // Output the result printf("Manhattan Distance = %d\\n", distance); return 0; }
Output
Here is an example of how the program runs:
Enter x1 and y1: 2 3 Enter x2 and y2: 5 7 Manhattan Distance = 7
In this example, the points are (2, 3)
and (5, 7)
. The Manhattan distance is calculated as:
- Absolute difference in x-coordinates:
|5 - 2| = 3
- Absolute difference in y-coordinates:
|7 - 3| = 4
- Sum of these differences:
3 + 4 = 7
Explanation
The program follows these steps:
-
Input: The user is prompted to enter the coordinates of two points. These values are read using the
scanf
function. -
Calculation:
-
The program calculates the absolute difference between the x-coordinates using the
abs
function from thestdlib.h
library. - Similarly, it calculates the absolute difference between the y-coordinates.
- The two absolute differences are added together to find the Manhattan distance.
-
The program calculates the absolute difference between the x-coordinates using the
-
Output: The result is displayed as an integer using the
printf
function.
The Manhattan distance is particularly useful in scenarios where movement is restricted to horizontal and vertical paths, such as grid-based games or city navigation systems.
This program demonstrates the simplicity of calculating it using basic arithmetic and the abs
function.