Bresenham’s Line Generation Algorithm
Last Updated :
23 Jul, 2025
Given the coordinate of two points A(x1, y1) and B(x2, y2). The task is to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates.
Examples:
Input : A(0,0), B(4,4)
Output : (0,0), (1,1), (2,2), (3,3), (4,4)
Input : A(0,0), B(4,2)
Output : (0,0), (1,0), (2,1), (3,1), (4,2)
Below are some assumptions to keep the algorithm simple.
- We draw lines from left to right.
- x1 < x2 and y1< y2
- Slope of the line is between 0 and 1. We draw a line from lower left to upper right.
Naive Approach:
C++
// A naive way of drawing line
void naiveDrawLine(x1, x2, y1, y2)
{
m = (y2 - y1) / (x2 - x1);
for (x = x1; x <= x2; x++) {
// Assuming that the round function finds
// closest integer to a given float.
y = round(mx + c);
print(x, y);
}
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
// A naive way of drawing line
public static void naiveDrawLine(x1, x2, y1, y2)
{
m = (y2 - y1) / (x2 - x1);
for (x = x1; x <= x2; x++)
{
// Assuming that the round function finds
// closest integer to a given float.
y = round(mx + c);
print(x, y);
}
}
public static void main(String[] args) {}
}
// This code is contributed by akashish__
Python3
# A naive way of drawing line
def naiveDrawLine(x1, x2, y1, y2):
m = (y2 - y1) / (x2 - x1)
# for (x = x1; x <= x2; x++) {
for x in range(x1, x2 + 1):
# Assuming that the round function finds
# closest integer to a given float.
y = round(mx + c)
print(x, y)
# This code is contributed by akashish__
C#
using System;
public class GFG {
// A naive way of drawing line
public static void naiveDrawLine(x1, x2, y1, y2)
{
m = (y2 - y1) / (x2 - x1);
for (x = x1; x <= x2; x++) {
// Assuming that the round function finds
// closest integer to a given float.
y = round(mx + c);
print(x, y);
}
}
static public void Main()
{
// Code
}
}
// This code is contributed by akashish__
JavaScript
// A naive way of drawing line
function naiveDrawLine(x1, x2, y1, y2)
{
m = (y2 - y1) / (x2 - x1);
for (x = x1; x <= x2; x++) {
// Assuming that the round function finds
// closest integer to a given float.
y = Math.round(mx + c);
print(x, y);
}
}
// This code is contributed by garg28harsh.
The above algorithm works, but it is slow. The idea of Bresenham's algorithm is to avoid floating point multiplication and addition to compute mx + c, and then compute the round value of (mx + c) in every step. In Bresenham's algorithm, we move across the x-axis in unit intervals.
We always increase x by 1, and we choose about next y, whether we need to go to y+1 or remain on y. In other words, from any position (Xk, Yk) we need to choose between (Xk + 1, Yk) and (Xk + 1, Yk + 1).

We would like to pick the y value (among Yk + 1 and Yk) corresponding to a point that is closer to the original line.
We need a decision parameter to decide whether to pick Yk + 1 or Yk as the next point. The idea is to keep track of slope error from the previous increment to y. If the slope error becomes greater than 0.5, we know that the line has moved upwards one pixel and that we must increment our y coordinate and readjust the error to represent the distance from the top of the new pixel – which is done by subtracting one from the error.
C++
// Modifying the naive way to use a parameter
// to decide next y.
void withDecisionParameter(x1, x2, y1, y2)
{
m = (y2 - y1) / (x2 - x1);
slope_error = [Some Initial Value];
for (x = x1, y = y1; x = 0.5) {
y++;
slope_error -= 1.0;
}
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
// Modifying the naive way to use a parameter
// to decide next y.
public static void withDecisionParameter(x1, x2, y1, y2)
{
m = (y2 - y1) / (x2 - x1);
slope_error = [Some Initial Value];
for (x = x1, y = y1; x = 0.5) {
y++;
slope_error -= 1.0;
}
}
public static void main (String[] args) {
}
}
// This code is contributed by akashish__
Python3
# Modifying the naive way to use a parameter
# to decide next y.
def withDecisionParameter(x1, x2, y1, y2):
m = (y2 - y1) / (x2 - x1)
slope_error = [Some Initial Value]
for x in range(0.5,x1) and y in range(y1):
y += 1
slope_error -= 1.0
# This code is contributed by akashish__
C#
using System;
public class GFG {
// Modifying the naive way to use a parameter
// to decide next y.
public static void withDecisionParameter(x1, x2, y1, y2)
{
m = (y2 - y1) / (x2 - x1);
slope_error = [ Some Initial Value ];
for (x = x1, y = y1; x = 0.5) {
y++;
slope_error -= 1.0;
}
}
static public void Main() {}
}
// This code is contributed by akashish__
JavaScript
// Modifying the naive way to use a parameter
// to decide next y.
function withDecisionParameter(x1, x2, y1, y2)
{
m = (y2 - y1) / (x2 - x1);
slope_error = [Some Initial Value];
for (x = x1, y = y1; x = 0.5) {
y++;
slope_error -= 1.0;
}
}
// This code is contributed by akashish__
How to avoid floating point arithmetic
The above algorithm still includes floating point arithmetic. To avoid floating point arithmetic, consider the value below value m.
- m = (y2 - y1)/(x2 - x1)
- We multiply both sides by (x2 - x1)
- We also change slope_error to slope_error * (x2 - x1). To avoid comparison with 0.5, we further change it to slope_error * (x2 - x1) * 2.
- Also, it is generally preferred to compare with 0 than 1.
C++
// Modifying the above algorithm to avoid floating
// point arithmetic and use comparison with 0.
void bresenham(x1, x2, y1, y2)
{
m_new = 2 * (y2 - y1) slope_error_new =
[Some Initial Value] for (x = x1, y = y1; x = 0)
{
y++;
slope_error_new -= 2 * (x2 - x1);
}
}
Java
public static void bresenham(int x1, int x2, int y1, int y2) {
int m_new = 2 * (y2 - y1);
int slope_error_new = 0;
for (int x = x1, y = y1; x = 0;) {
y++;
slope_error_new -= 2 * (x2 - x1);
}
}
// This code is contributed by ishankhandelwals.
Python3
# Modifying the above algorithm to avoid floating
# point arithmetic and use comparison with 0.
def bresenham(x1, x2, y1, y2):
m_new = 2 * (y2 - y1)
slope_error_new = 0
y = y1
for x in range(x1, 0, -1) {
y += 1
slope_error_new -= 2 * (x2 - x1)
# This code is contributed by akashish__
C#
using System;
public class GFG{
// Modifying the above algorithm to avoid floating
// point arithmetic and use comparison with 0.
public static void bresenham(x1, x2, y1, y2)
{
m_new = 2 * (y2 - y1);
slope_error_new = [Some Initial Value];
for (int x = x1,int y = y1; x = 0)
{
y++;
slope_error_new -= 2 * (x2 - x1);
}
}
static public void Main (){
// Code
}
}
// This code is contributed by akashish__
JavaScript
// Modifying the above algorithm to avoid floating
// point arithmetic and use comparison with 0.
function bresenham(x1, x2, y1, y2)
{
let m_new = 2 * (y2 - y1);
let slope_error_new = 0;
for (let x = x1, let y = y1; x = 0) {
y++;
slope_error_new -= 2 * (x2 - x1);
}
}
// This code is contributed by akashish__
The initial value of slope_error_new is 2*(y2 - y1) - (x2 - x1).
Below is the implementation of the above algorithm:
C++
// C++ program for Bresenham’s Line Generation
// Assumptions :
// 1) Line is drawn from left to right.
// 2) x1 < x2 and y1 < y2
// 3) Slope of the line is between 0 and 1.
// We draw a line from lower left to upper
// right.
#include <bits/stdc++.h>
using namespace std;
// function for line generation
void bresenham(int x1, int y1, int x2, int y2)
{
int m_new = 2 * (y2 - y1);
int slope_error_new = m_new - (x2 - x1);
for (int x = x1, y = y1; x <= x2; x++) {
cout << "(" << x << "," << y << ")\n";
// Add slope to increment angle formed
slope_error_new += m_new;
// Slope error reached limit, time to
// increment y and update slope error.
if (slope_error_new >= 0) {
y++;
slope_error_new -= 2 * (x2 - x1);
}
}
}
// driver code
int main()
{
int x1 = 3, y1 = 2, x2 = 15, y2 = 5;
// Function call
bresenham(x1, y1, x2, y2);
return 0;
}
Java
// Java program for Bresenhams Line Generation
// Assumptions :
// 1) Line is drawn from left to right.
// 2) x1 < x2 and y1 < y2
// 3) Slope of the line is between 0 and 1.
// We draw a line from lower left to upper
// right.
class GFG {
// function for line generation
static void bresenham(int x1, int y1, int x2, int y2)
{
int m_new = 2 * (y2 - y1);
int slope_error_new = m_new - (x2 - x1);
for (int x = x1, y = y1; x < = x2; x++) {
System.out.print(
"
(" + x + ", " + y + ")\n
& quot;);
// Add slope to increment angle formed
slope_error_new += m_new;
// Slope error reached limit, time to
// increment y and update slope error.
if (slope_error_new& gt; = 0) {
y++;
slope_error_new -= 2 * (x2 - x1);
}
}
}
// Driver code
public static void main(String[] args)
{
int x1 = 3, y1 = 2, x2 = 15, y2 = 5;
// Function call
bresenham(x1, y1, x2, y2);
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python 3 program for Bresenham’s Line Generation
# Assumptions :
# 1) Line is drawn from left to right.
# 2) x1 < x2 and y1 < y2
# 3) Slope of the line is between 0 and 1.
# We draw a line from lower left to upper
# right.
# function for line generation
def bresenham(x1, y1, x2, y2):
m_new = 2 * (y2 - y1)
slope_error_new = m_new - (x2 - x1)
y = y1
for x in range(x1, x2+1):
print("(", x, ",", y, ")\n")
# Add slope to increment angle formed
slope_error_new = slope_error_new + m_new
# Slope error reached limit, time to
# increment y and update slope error.
if (slope_error_new >= 0):
y = y+1
slope_error_new = slope_error_new - 2 * (x2 - x1)
# Driver code
if __name__ == '__main__':
x1 = 3
y1 = 2
x2 = 15
y2 = 5
# Function call
bresenham(x1, y1, x2, y2)
# This code is contributed by ash264
C#
// C# program for Bresenhams Line Generation
// Assumptions :
// 1) Line is drawn from left to right.
// 2) x1 < x2 and y1< y2
// 3) Slope of the line is between 0 and 1.
// We draw a line from lower left to upper
// right.
using System;
class GFG {
// function for line generation
static void bresenham(int x1, int y1, int x2, int y2)
{
int m_new = 2 * (y2 - y1);
int slope_error_new = m_new - (x2 - x1);
for (int x = x1, y = y1; x < = x2; x++) {
Console.Write(" (" + x + "
, " + y + ")\n
& quot;);
// Add slope to increment angle formed
slope_error_new += m_new;
// Slope error reached limit, time to
// increment y and update slope error.
if (slope_error_new& gt; = 0) {
y++;
slope_error_new -= 2 * (x2 - x1);
}
}
}
// Driver code
public static void Main()
{
int x1 = 3, y1 = 2, x2 = 15, y2 = 5;
// Function call
bresenham(x1, y1, x2, y2);
}
}
// This code is contributed by nitin mittal.
PHP
<?php
// PHP program for Bresenham’s
// Line Generation Assumptions :
// 1) Line is drawn from
// left to right.
// 2) x1 < x2 and y1 < y2
// 3) Slope of the line is
// between 0 and 1.
// We draw a line from lower
// left to upper right.
// function for line generation
function bresenham($x1, $y1, $x2, $y2)
{
$m_new = 2 * ($y2 - $y1);
$slope_error_new = $m_new - ($x2 - $x1);
for ($x = $x1, $y = $y1; $x <= $x2; $x++)
{
echo "(" ,$x , "," , $y, ")\n";
// Add slope to increment
// angle formed
$slope_error_new += $m_new;
// Slope error reached limit,
// time to increment y and
// update slope error.
if ($slope_error_new >= 0)
{
$y++;
$slope_error_new -= 2 * ($x2 - $x1);
}
}
}
// Driver Code
$x1 = 3; $y1 = 2; $x2 = 15; $y2 = 5;
// Function call
bresenham($x1, $y1, $x2, $y2);
// This code is contributed by nitin mittal.
?>
JavaScript
// Javascript program for Bresenhams Line Generation
function plotPixel(x1, y1, x2,
y2, dx, dy,
decide)
{
// pk is initial decision making parameter
// Note:x1&y1,x2&y2, dx&dy values are interchanged
// and passed in plotPixel function so
// it can handle both cases when m>1 & m<1
let pk = 2 * dy - dx;
for (let i = 0; i <= dx; i++) {
if(decide == 0){
console.log(x1 + "," + y1);
}
else{
console.log(y1 + "," + x1);
}
// checking either to decrement or increment the
// value if we have to plot from (0,100) to
// (100,0)
if (x1 < x2)
x1++;
else
x1--;
if (pk < 0) {
// decision value will decide to plot
// either x1 or y1 in x's position
if (decide == 0) {
pk = pk + 2 * dy;
}
else
pk = pk + 2 * dy;
}
else {
if (y1 < y2)
y1++;
else
y1--;
pk = pk + 2 * dy - 2 * dx;
}
}
}
// Driver code
let x1 = 100, y1 = 110, x2 = 125, y2 = 120, dx, dy;
dx = Math.abs(x2 - x1);
dy = Math.abs(y2 - y1);
// If slope is less than one
if (dx > dy) {
// passing argument as 0 to plot(x,y)
plotPixel(x1, y1, x2, y2, dx, dy, 0);
}
// if slope is greater than or equal to 1
else {
// passing argument as 1 to plot (y,x)
plotPixel(y1, x1, y2, x2, dy, dx, 1);
}
// This code is contributed by akashish__ and kalil
Output(3,2)
(4,3)
(5,3)
(6,3)
(7,3)
(8,4)
(9,4)
(10,4)
(11,4)
(12,5)
(13,5)
(14,5)
(15,5)
Time Complexity: O(x2 - x1)
Auxiliary Space: O(1)
The above explanation is to provide a rough idea behind the algorithm. For detailed explanation and proof, readers can refer below references.
The above program only works if the slope of the line is less than 1. Here is a program implementation for any kind of slope.
Output100,110
101,110
102,111
103,111
104,112
105,112
106,112
107,113
108,113
109,114
110,114
111,114
112,115
113,115
114,116
115,116
116,116
117,117
118,117
119,118
120,118
121,118
122,119
123,119
124,120
125,120
Related Articles:
- Mid-Point Line Generation Algorithm
- DDA algorithm for line drawing
Bresenham's Line Algorithm
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem