Reputation: 23
I have made a program in C.
What it does or should do is draw a filled circle by displaying values of a matrix.
You can input the values of the radius of the circle, the position of the center of the circle relative to the center of the matrix and the size of the matrix i.e. resolution.
So when it gives values of the cells of the matrix, it checks if the cell (or point) is inside the circle.
For each cell there is a point determined by the variables x and y. When the point is inside the circle, that means that the number that we get by calculating the equation of a circle with the x and y values is less than the radius of the circle squared.
If the point is inside the circle, the program makes the value of the corresponding cell 1. Otherwise it makes it 0.
So in the end it should display the matrix and it should look like a bunch of zeroes and inside there is a filled circle made of ones.
The problem:
The program works, I can type in the values it needs (for example radius is 50, x position is 0, y position is 0 and resolution (matrix size) is 150), but when it is supposed to display the matrix it only prints zeroes.
Is there anything fundamentally wrong with my program? What could cause the problem?
Thanks in advance!
My code:
#include <stdio.h>
int main()
{
float x = 0, y = 0, ypos= 0 , xpos = 0, radius = 0, rsqrd = 0, rcheck = 0;
int matsize = 0, i, j;
printf("Value of radius:");
scanf("%f" , &radius);
printf("Position of circle on the x axis:");
scanf("%f" , &xpos);
printf("Position of circle on the y axis:");
scanf("%f" , &ypos);
printf("Resolution:");
scanf("%d" , &matsize);
printf("\n");
rsqrd = radius*radius; //rsqrd is equal to radius squared.
x = -1*(matsize/2); //with this I make sure that the x and y values start from the top right corner of the matrix, so that each x, y value corresponds to the correct cell position (i, j)
y = matsize/2;
int mat[matsize][matsize];
for(i = 0; i < matsize; i++)
{
for(j = 0; j < matsize; j++)
{
rcheck = ((y - ypos)*(y - ypos)) + ((x - xpos)*(x - xpos)); // calculating the equation of the circle with the x and y values taking the offset into account
if(rcheck <= rsqrd)
{
mat[i][j] = 1;
}
else
{
mat[i][j] = 0;
}
x = x+1; //stepping the values of x and y so they stay with the corresponding cell
}
y = y-1;
}
for(i = 0; i < matsize; i++) // displaying the matrix
{
for(j = 0; j < matsize; j++)
{
printf("%d ",mat[i][j]);
}
printf("\n");
}
return 0;
}
Upvotes: 0
Views: 1214
Reputation: 24547
You forgot to reset x
when decrementing y
.
Try this:
for(i = 0; i < matsize; i++)
{
for(j = 0; j < matsize; j++)
{
rcheck = ((y - ypos)*(y - ypos)) + ((x - xpos)*(x - xpos)); // calculating the equation of the circle with the x and y values taking the offset into account
if(rcheck <= rsqrd)
{
mat[i][j] = 1;
}
else
{
mat[i][j] = 0;
}
x = x+1; //stepping the values of x and y so they stay with the corresponding cell
}
y = y-1;
x -= matsize; // <-- Reset x to start of row
}
Upvotes: 2