Navigation Menu

Currently the navigation bar is not functioning. Use the Blog Archive or the Google Custom Search to find content.

Saturday 15 June 2013

C Program for DDA (graphics algorithm)

Given below is a C program to draw a line using DDA algorithm.

Code :
#include<stdio.h>
#include<conio.h>
#include<graphics.h>
#include<math.h>
int sign(int nd)
{
    if(nd>0)
        return +1;
    else if(nd<0)
        return -1;
    else
        return 0;
}
void main()
{
    int gd=DETECT,gm,i=1,j;//DETECT is macro defined in graphics.h
    int x1,x2,y1,y2,length;
    float dx,dy,ndx,ndy,x,y;
    initgraph(&gd,&gm,"d:\\tc\\bgi");//initialize graphic mode
    setbkcolor(DARKGRAY);//set the background color
    printf("Enter x1:");
    scanf("%d",&x1);
    printf("Enter y1:");
    scanf("%d",&y1);
    printf("Enter x2:");
    scanf("%d",&x2);
    printf("Enter y2:");
    scanf("%d",&y2);
    dx=x2-x1;
    dy=y2-y1;
    if(abs(dx)>=abs(dy))
        length=abs(dx);
    else
        length=abs(dy);
    ndx=dx/length;
    ndy=dy/length;
    x=x1+(0.5*sign(ndx));
    y=y1+(0.5*sign(ndy));
    while(i<=length)
    {
        putpixel(x,y,4);
        x=x+ndx;
        y=y+ndy;
        i=i+1;
    }
    getch();
    closegraph();
}
Output :


Note : In the above screenshot the line is hardly visible. The image above is a grayscale of original image.

Note : The program above has been tested using TurboCPP. Leave a comment if you feel the program is incorrect and/or has errors and/or if the program and its output don't match. Please report about broken links.

No comments:

Post a Comment