Midpoint Circle Algorithm Using C Programming

🎯 Introduction

The "Midpoint Circle Algorithm" is a classic computer graphics algorithm used to draw circles on a pixel grid. It is an efficient and elegant way to generate the points lying on the circumference of a circle centered at (x, y) with a given radius 'r'. This algorithm is particularly useful in graphics applications where direct access to pixels is available.

In this blog post, we will explore the Midpoint Circle Algorithm implemented using the C programming language. We'll provide a detailed explanation of the concept and the step-by-step execution of the algorithm. Additionally, we'll optimize and update the code to fit modern standards and remove outdated dependencies.

🎯 Concept and Explanation

The Midpoint Circle Algorithm works by plotting only a limited set of points lying on the circumference of the circle rather than plotting all points. The algorithm takes advantage of the symmetry of circles to determine the next points to plot, thus reducing the computational effort required.

Step-by-step execution of the Midpoint Circle Algorithm:

🎯 Midpoint Circle Algorithm Code

Below is the Midpoint Circle Algorithm using the C programming language:


#include <stdio.h>

#include <graphics.h>


void drawCircle(int x1, int y1, int r);


int main()

{

    int gd = DETECT, gm;

    int x, y, r;


    printf("Enter the Midpoint and Radius: ");

    scanf("%d%d%d", &x, &y, &r);


    initgraph(&gd, &gm, "");


    drawCircle(x, y, r);


    getch();

    closegraph();

    return 0;

}


void drawCircle(int x1, int y1, int r)

{

    int x = 0, y = r;

    int p = 1 - r;


    void plotPoints(int, int, int, int);


    plotPoints(x1, y1, x, y);


    while (x < y)

    {

        x++;

        if (p < 0)

            p += 2 * x + 1;

        else

        {

            y--;

            p += 2 * (x - y) + 1;

        }

        plotPoints(x1, y1, x, y);

    }

}


void plotPoints(int xctr, int yctr, int x, int y)

{

    putpixel(xctr + x, yctr + y, 1);

    putpixel(xctr - x, yctr + y, 1);

    putpixel(xctr + x, yctr - y, 1);

    putpixel(xctr - x, yctr - y, 1);

    putpixel(xctr + y, yctr + x, 1);

    putpixel(xctr - y, yctr + x, 1);

    putpixel(xctr + y, yctr - x, 1);

    putpixel(xctr - y, yctr - x, 1);

}

🎯 Explanation of the Source Code

🎯 Summary

In this blog post, we learned about the "Midpoint Circle Algorithm" and its implementation using the C programming language. The algorithm efficiently draws circles by utilizing the concept of symmetry and plotting only specific points on the circumference. We explored the step-by-step execution of the algorithm and provided an updated and optimized C code for drawing circles. This algorithm is valuable in computer graphics and various graphical applications due to its simplicity and efficiency.

🎯 Key Points