Blog Archives

Line Drawing using DDA Algorithm

//Line Drawing using DDA Algorithm

#include<stdio.h>
#include<graphics.h>
#include<conio.h>
#include<stdlib.h>

int main()
{
	int i, start_x, start_y, end_x, end_y, steps, dx, dy;
	float x, y, x_incr, y_incr;

    //// init graphics driver Turbo C++
    //int driver = DETECT, mode = DETECT;
	//initgraph(&driver, &mode, "C:\TC\BGI");
	
	// init graphics driver Dev C++
	initwindow(640, 400, "My Window");

	//getting cords from user
	printf("Enter the Start cords (x and y): ");
	scanf("%d%d", &start_x, &start_y);
	
	printf("Enter the End cords (x and y): ");
	scanf("%d%d", &end_x, &end_y);

	//setting up drawing parameters
	dx = end_x - start_x;
	dy = end_y - start_y;
	if(dx>dy)
		steps=dx;
	else
		steps=dy;

	x_incr = (float)dx/steps;
	y_incr = (float)dy/steps;

	printf("Parameters are\ns_x : %d\ns_y : %d\ne_x : %d\ne_y : %d\ndx : %d\ndy : %d\nsteps : %d\nx_i : %f\ny_i : %f\n", start_x, start_y, end_x, end_y, dx, dy, steps, x_incr, y_incr);
	printf("press any key to draw line\n");
	
	system( "cls");

	//drawing line
	x=start_x;
	y=start_y;
	for(i=0; i<=steps; i++)
	{
		putpixel((int)x, (int)y, 15);
		x += x_incr;
		y += y_incr;
	}
	
	getch();

	//closing driver
	closegraph();
	return 0;
}