C program for midpoint circle algorithm.

Posted by Mangesh on June 13, 2018

Description :

Midpoint Circle Algorithm: A circle is defined as a set of points that are all at a given distance r from a center positioned at . (xc ,yc).
This is represented mathematically by the equation
=> (x - xc)2 + (y - yc)2 = r2
Using equation (1) we can calculate the value of y for each given value of x as
=> y = yc +- sqrt(r2 - (x - xc)2)
Thus one could calculate different pairs by giving step increments to x and calculating the corresponding value of y. But this approach involves considerable computation at each step and also the resulting circle has its pixels sparsely plotted for areas with higher values of the slope of the curve.

Program :

#include<stdio.h>
#include<conio.h>
#include<graphics.h>
void drawcircle(int x0, int y0, int radius)
{
  int x = radius;
  int y = 0;
  int err = 0;
  while (x >= y)
  {
    putpixel(x0 + x, y0 + y, 7);
    putpixel(x0 + y, y0 + x, 7);
    putpixel(x0 - y, y0 + x, 7);
    putpixel(x0 - x, y0 + y, 7);
    putpixel(x0 - x, y0 - y, 7);
    putpixel(x0 - y, y0 - x, 7);
    putpixel(x0 + y, y0 - x, 7);
    putpixel(x0 + x, y0 - y, 7);
    if (err <= 0)
    {
      y += 1;
      err += 2*y + 1;
    }
    if (err > 0)
    {
      x -= 1;
      err -= 2*x + 1;
    }
  }
}
void main()
{
  int gdriver=DETECT, gmode, error, x, y, r;
  initgraph(&gdriver, &gmode, "c:\\turboc3\\bgi");

  printf("Enter radius of circle: ");
  scanf("%d", &r);
  printf("Enter co-ordinates of center(x and y): ");
  scanf("%d%d", &x, &y);
  drawcircle(x, y, r);
  getch();
}

Output :

c program for shortest job first Executed and Tested in Turbo C 3.2

Written with from Mangesh.

Related Post
1 C program for scaling of 2D object.
2 C program to tramsform 2D objects.
3 C program to draw a line.
4 C program to draw a circle.
5 C program to draw a rectangle.
6 C program for DDA algorithm to generate line.
7 C program for midpoint circle algorithm.
Latest Post
1 C program to implement Queue using linked list.
2 C program for binary search tree (BST).
3 C program to search an element in linked list.
4 C program for postorder traversal in binary tree.
5 C program for preorder traversal in binary tree.