Given two coordinates, find the slope of a straight line.
Examples:
Input : x1 = 4, y1 = 2,
x2 = 2, y2 = 5
Output : Slope is -1.5
Approach: To calculate the slope of a line you need only two points from that line, (x1, y1) and (x2, y2). The equation used to calculate the slope from two points is:

Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
float slope( float x1, float y1, float x2, float y2)
{
if (x2 - x1 != 0)
return (y2 - y1) / (x2 - x1);
return INT_MAX;
}
int main()
{
float x1 = 4, y1 = 2;
float x2 = 2, y2 = 5;
cout << "Slope is: " << slope(x1, y1, x2, y2);
return 0;
}
|
Java
import java.io.*;
class GFG {
static float slope( float x1, float y1, float x2,
float y2)
{
if (x2 - x1 != 0 )
return (y2 - y1) / (x2 - x1);
return Integer.MAX_VALUE;
}
public static void main(String[] args)
{
float x1 = 4 , y1 = 2 ;
float x2 = 2 , y2 = 5 ;
System.out.println( "Slope is: "
+ slope(x1, y1, x2, y2));
}
}
|
Python
def slope(x1, y1, x2, y2):
if (x2 - x1 ! = 0 ):
return ( float )(y2 - y1) / (x2 - x1)
return sys.maxint
x1 = 4
y1 = 2
x2 = 2
y2 = 5
print "Slope is:" , slope(x1, y1, x2, y2)
|
C#
using System;
public static class GFG {
public static float slope( float x1, float y1, float x2,
float y2)
{
if (x2 - x1 != 0F) {
return (y2 - y1) / (x2 - x1);
}
return int .MaxValue;
}
internal static void Main()
{
float x1 = 4F;
float y1 = 2F;
float x2 = 2F;
float y2 = 5F;
Console.Write( "Slope is: " );
Console.Write(slope(x1, y1, x2, y2));
}
}
|
PHP
<?php
function slope( $x1 , $y1 , $x2 , $y2 )
{
if ( $x1 == $x2 )
{
return PHP_INT_MAX;
}
return ( $y2 - $y1 ) /
( $x2 - $x1 );
}
$x1 = 4;
$y1 = 2;
$x2 = 2;
$y2 = 5;
echo "Slope is: "
, slope( $x1 , $y1 ,
$x2 , $y2 );
?>
|
Javascript
function slope(x1, y1, x2, y2)
{
if (x2 - x1 != 0)
{
return (y2 - y1) / (x2 - x1);
}
return Number.MAX_VALUE;
}
var x1 = 4;
var y1 = 2;
var x2 = 2;
var y2 = 5;
console.log( "Slope is: " + slope(x1, y1, x2, y2));
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
17 Feb, 2023
Like Article
Save Article