COMPUTER GRAPHICS - DDA ALGORITHM !!


Digital Differential Analyzer (DDA) algorithm is the simple line generation algorithm.
Step 1 − Get the input of two end points (X0,Y0) and (X1,Y1).
Step 2 − Calculate the difference between two end points.
                dx = X1 - X0
                dy = Y1 - Y0
Step 3 − Based on the calculated difference in step-2, you need to identify the number of steps to put pixel. If dx > dy, then you need more steps in x coordinate; otherwise in y coordinate.
            if (absolute(dx) > absolute(dy))
               Steps = absolute(dx);
            else
               Steps = absolute(dy);
Step 4 − Calculate the increment in x coordinate and y coordinate.
                Xincrement = dx / (float) steps;
                Yincrement = dy / (float) steps;
Step 5 − Put the pixel by successfully incrementing x and y coordinates accordingly and complete the drawing of the line.
            for(int i=0; i < Steps; i++)
            {
               = x + Xincrement;
               = y + Yincrement;
               putpixel(Round(x), Round(y));
            }


// C program for DDA line generation
#include<stdio.h>
#include<graphics.h>
//Function for finding absolute value
int abs (int n)
{
    return ( (n>0) ? n : ( n * (-1)));
}
//DDA Function for line generation
void DDA(int X0, int Y0, int X1, int Y1)
{
    // calculate dx & dy
    int dx = X1 - X0;
    int dy = Y1 - Y0;
    // calculate steps required for generating pixels
    int steps = abs(dx) > abs(dy) ? abs(dx) : abs(dy);
    // calculate increment in x & y for each steps
    float Xinc = dx / (float) steps;
    float Yinc = dy / (float) steps;
    // Put pixel for each step
    float X = X0;
    float Y = Y0;
    for (int i = 0; i <= steps; i++)
    {
        putpixel (X,Y,RED);  // put pixel at (X,Y)
        X += Xinc;           // increment in x at each step
        Y += Yinc;           // increment in y at each step
        delay(100);          // for visualization of line-
                             // generation step by step
    }
}
// Driver program
int main()
{
    int gd = DETECT, gm;
    // Initialize graphics function
    initgraph (&gd, &gm, "");  
    int X0, Y0, X1, Y1;
cin>>X0,Y0,X1,Y1;
    DDA(-50, -50, 200, 200);
    return 0;

}

OUTPUT:-

Want a code for Dotted and Thick Line using DDA. Leave your email id in the comment box.



Comments