Bresenham's line drawing Code - c

I'm trying to draw a line in C language using Bresenham's algorithm.I'm using turbo C++ in dosbox for windows 7 to implement this code.While compiling i'm not getting any error but when i run the code the programs terminates after obtaining the 2 co-ordinates.Please Help..
the message on compiling is as follows..
the directories path is as follows
My code..
# include <stdio.h>
# include <conio.h>
# include <graphics.h>
void main()
{
int dx,dy,x,y,p,x1,y1,x2,y2;
int gd,gm;
clrscr();
printf("\n\n\tEnter the co-ordinates of first point : ");
scanf("%d %d",&x1,&y1);
printf("\n\n\tEnter the co-ordinates of second point : ");
scanf("%d %d",&x2,&y2);
dx = (x2 - x1);
dy = (y2 - y1);
p = 2 * (dy) - (dx);
x = x1;
y = y1;
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"e:\\tc\\bgi");
putpixel(x,y,WHITE);
while(x <= x2)
{
if(p < 0)
{
x=x+1;
y=y;
p = p + 2 * (dy);
}
else
{
x=x+1;
y=y+1;
p = p + 2 * (dy - dx);
}
putpixel(x,y,WHITE);
}
getch();
closegraph();
}

OP should post input that was used.
The posted sample code does not work is x1 > x2 nor y1 > y2. This is one set of input that would stop the routine abruptly. To fix, the dx and dy should be based on the absolute value and the incremental x & y steps need to be independently +1 or -1.
An input of 3,4 instead of 3 4 (comma vs. whitespace) will also mess up the routine.
In the while loop, recommend if(p <= 0).
OP's "... code the programs terminates after obtaining the 2 co-ordinates." is not detailed enough, for of course the code should terminate sometime after obtaining the 2 co-ordinates. But OP does not detail where it terminates too early.

This is a typical perfect point to start the debugger and go through the code step-by-step, watching any variables. If a debugger is unavailable, printf debugging to the console is a backup alternative.
A first tip is to check that these lines do not generate an error/exception:
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"e:\\tc\\bgi");
putpixel(x,y,WHITE);

Nice program. But, you haven't initialized any loop as well as lines coded in while-loop were partially incorrect. Here is my try:-
i = 1; // loop initialization
do {
putpixel(x, y, 15);
while(p >= 0) {
y = y + 1;
p = p - (2 * dx);
}
x = x + 1;
p = p + (2 * dy);
i = i + 1;
}
while(i <= dx);

A way to rectify the problem is by changing the path in the initgraph function according to the address mentioned in the screenshot.
detectgraph(&gd,&gm);
initgraph(&gd,&gm,"C:\\TURBOC3\\bgi");
putpixel(x,y,WHITE);

Related

A Program to print the last n, (n+1), (n+2),....(n+31) number of digits of the number input by the user, where n = 1, otherwise print "0+error.extra"

#include <stdio.h>
int main()
{
signed int x;
int x1 = 0, x2 = 10, final, loop = 1, y = 10, c;
printf("Enter the value of X.\n");
scanf("%d", &x);
printf("Value Scanned:%d\n", x);
again:
if (loop <= 32)
{
if (x >= x1 && x < x2)
{
final = x - x1;
printf("%d", final);
y = y * 10;
x1 = 0;
x2 = 0;
++loop;
goto again;
}
else
{
c = x2 - x1;
if (x1 == x2)
{
x2 += y;
goto again;
}
else if (c == y)
{
x1 += y;
x2 += y;
goto again;
}
else
{
printf("Error in Process");
goto ending;
}
}
}
else
{
printf("0+error, extra long input");
}
ending:
return 0;
}
Flowchart:
I am a beginner in C-language and only know how to use If-else, Switch, Goto statements, with basic knowledge of how to integrate basic level loops. So please tell me what/where I am wrong instead of telling me how to use arrays because I don't know them, etc. This is my most complex code until now.
Now for Explanation of Coding,
I wrote X1 as the lower value and X2 as the upper value while first keeping a difference = Y(initially 10) between them.
Continuously increasing the value of X1 and X2 by Y(10) together simultaneously, I will arrive in between an intersection where my x(input) lies.
Eg-
x=568
then X1 and X2 will keep on increasing until they reach X1 = 560 and X2 = 570, then they will do Final = X(568) - X1(560) and print it.
since it can only happen for 32-digits long, so I wrote loop = 0 and only processing my main statement till loop is smaller than or equal to 32, otherwise printing "0+error".
then I put Y = Y * 10 every time the value was within my specified range.
It should give me the values like Last digit, then last 2 digits, then last 3 digits,etc. but after scanning the value, it isn't exciting at all.
Evaluating what you are attempting to do, I reworked your code to make it a bit more structured without utilizing arrays at that seemed to be something you wanted to avoid at this time. However, these days, the use of the goto statement is usually avoided since functionality such as for loops, do/while loops, and while loops offer better clarity to coding. With that in mind, following is a snippet of code that provides the functionality it looks like you want.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x, x1, x2, y = 10, counter = 0, last_digit;
printf("Please enter a number: ");
scanf("%d", &x);
if (x < 0) /* Just in case a negative integer is entered */
{
x = x * -1;
}
while (1) /* Use a while loop with associated break statements to avoid goto and label statements */
{
x1 = 0;
x2 = 10;
counter += 1;
while (1)
{
if (x >= x1 && x <= x2)
{
last_digit = x - x1;
if (counter == 1)
{
printf("The last digit is: %d\n", last_digit);
}
else
{
printf("The next digit is: %d\n", last_digit);
}
break;
}
x1 += y;
x2 += y;
}
x = x / 10; /* Perform integer division by ten to get to the next digit in the entered number */
if (x == 0) /* Once all digits have been processed the outer while loop can be exited */
{
break;
}
}
return 0;
}
Following are some key points.
As noted, the loop process using goto statements is replaced by two while loops; one while loop nested inside another while loop.
Utilizing integer division by ten, each digit can be ascertained and printed.
Utilizing the nested while loops with break statements allows for a more compact program.
Utilizing this code snippet, following is a sample test from the terminal.
#Dev:~/C_Programs/Console/LastDigit/bin/Release$ ./LastDigit
Please enter a number: 479824385
The last digit is: 5
The next digit is: 8
The next digit is: 3
The next digit is: 4
The next digit is: 2
The next digit is: 8
The next digit is: 9
The next digit is: 7
The next digit is: 4
Back in the day, the goto statement had its place in coding, but today it is pretty much an artifact.
Give that a try and see if it meets the spirit of your project.

Validating a triangle in C

I'm new in C, so I try to create a program that calculate the area of triangle as a start.
Calculating the area is easy when the triangle exists, however the validation of straight line is working partially.
Example:
A(0,-4) B(1,0) C(4,12) does not produce straight line error.
but
A(4,12) B(1,0) C(0,-4) produce straight line error.
#include <stdio.h>
#include <math.h>
double square(double num){
return (num*num);
}
int main()
{
double x[5],y[5],a,b,c,angle,area;
printf("Hello there! Calculating the area of triangle.\n");
printf("Enter a coordinate A :\n");
scanf("%lf,%lf",&x[0],&y[0]);
printf("Enter another coordinate B :\n");
scanf("%lf,%lf",&x[1],&y[1]);
printf("Enter another coordinate C :\n");
scanf("%lf,%lf",&x[2],&y[2]);
// AB as base (a) , c is opposite side
a = sqrt( square((x[0]-x[1])) + square((y[0]-y[1])) );
b = sqrt( square((x[0]-x[2])) + square((y[0]-y[2])) );
c = sqrt( square(x[1]-x[2]) + square((y[1]-y[2])) );
double num = (square(a)+square(b)-square(c))/(2*a*b);
angle = acos(num);
area = .5*a*b*sin(angle);
//printf("%lf %lf %lf %lf %lf \n",a,b,c,num,angle);
if (num == 1 || num ==-1){
printf("That's a straight line.");
}else{
printf("Area of triangle is %lf\n",area);
}
return 0;
}
You can use a different test, and perhaps a different area formula. If you use Heron's formula, then once you have the lengths of the sides a, b, and c, you can compute:
double p = (a + b + c)/2;
double area = sqrt(p*(p-a)*(p-b)*(p-c));
You can detect if the triangle is valid by checking that p is greater than each of the sides.
double p = (a + b + c)/2;
if ((p > a) && (p > b) && (p > c)) {
double area = sqrt(p*(p-a)*(p-b)*(p-c));
printf("Area of triangle is %lf\n", area);
} else {
printf("I don't consider that a triangle.\n");
}
Try it online!
The problem in your code is double num = (square(a)+square(b)-square(c))/(2*a*b); gets evaluated to a number slightly larger than 1 in some cases. This can happen with floating point computations. In your case you can safely add if (num > 1) num = 1; after that line since cosine equation always will give you a value larger than 0 and less than 1 for triangles.
However there's a problem if two points overlap and a or b becomes zero. You will have to check for that and handle it as a special case if such input is expected by your code. (If two points overlap then they are collinear anyways. You can check the overlap by checking if any of a,b,c are zero)

How to print some information in the terminal while running a graphics.h based C program?

This is my first question in StackOverflow so forgive me for my mistakes in asking the question if any. I am trying to learn to use graphics.h library in C programming language as a part of the course curriculum and I am having trouble printing some information to the terminal in Linux while using libgraph. The printf() function prints the given information in the libgraph window instead of the terminal whereas I want it to print the information to the Linux terminal. Here are my code and screenshot of the output of this code Screenshot:
DDA algorithm screenshot of printf problem:
#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++)
{
printf("(%f,%f)",X,Y);
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 = 2, Y0 = 2, X1 = 14, Y1 = 16;
DDA(2, 2, 100, 100);
getch();
return 0;
}
What I want is that printf to print in the Linux terminal instead of the libgraph window.
Some, if not all implementations of libgraph have this line in one of the header files:
#define printf grprintf
So, they redefine printf with a macro, and you can't use it to print in the linux terminal. But since they don't redefine other output functions, you can use e. g.
fprintf(stdout, "(%f,%f)", X, Y), fflush(stdout); // or stderr instead of stdout
or puts for constant strings.
Or, even simpler, you can #undef printf after the #include<graphics.h> to get back the normal behavior.

How to find the numbers that satisfy (x - y * sqrt(2016.0)) / (y + sqrt(2016.0)) = 2016 using loops in C

I'm trying to find numbers that satisfy the clause (x - y * √ 2016) / (y + √ 2016) = 2016.
Number x and y can be rational numbers.
That's what I already tried:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int x, y;
for(x = 1; x < 10000; x++) {
for(y = 1; y < 10000; y++) {
if( (x - y * sqrt(2016.0)) / (y + sqrt(2016.0) ) == 2016) {
printf("Numbers are: %d and %d.", x, y);
}
}
}
return 0;
}
Using floating point math and brute force search to "solve" this problem is conceptionally a bad idea. This is because with FP math round-off error propagates in a non-intuitive way, and hence many equations that are solvable in a mathematical sense have no (exact) solution with FP numbers. So using FP math to approximate solutions of mathematical equations is inherently difficult.
I suggest a simplification of the problem before programming.
If one does this and only searches for integer solutions one would find that the only solutions are
x = -2016^2 = -4064256
y = -2016
Why: Just rearrange a bit and obtain
x = 2016*y + (2016 + y)*sqrt(2016)
Since sqrt(2016) is not an integer the term in the clause before the sqrt must be zero. Everything else follows from that.
In case a non-integer solution is desired, the above can be used to find the x for every y. Which even enumerates all solutions.
So this shows that simplification of a mathematical problem before attempted solution in a computer is usually mandatory (especially with FP math).
EDIT: In case you look for rational numbers, the same argument can be applied as for the integer case. Since sqrt(2016) is not a rational number, y must also be -2016. So for the rational case, the only solutions are the same as for the integers, i.e,
x = -2016^2 = -4064256
y = -2016
This is just the equation for a line. Here's an exact solution:
x = (sqrt(2016) + 2016)*y + 2016*sqrt(2016)
For any value of y, x is given by the above. The x-intercept is:
x = 2016*sqrt(2016)
y = 0
The y-intercept is:
x = 0
y = -2016*sqrt(2016)/(sqrt(2016)+2016)
numbers that satisfy (x - y * sqrt(2016.0)) / (y + sqrt(2016.0)) = 2016
Starting with #Tom Karzes
x = (sqrt(2016) + 2016)*y + 2016*sqrt(2016)
Let y = -2016
x = (sqrt(2016) + 2016)*-2016 + 2016*sqrt(2016)
x = 2016*-2016 = -4064256
So x,y = -4064256, -2016 is one exact solution.
With math, this is the only one.
With sqrt(x) not being exactly √x and peculiarities of double math, there may be other solutions that pass a C code simulation.
As a C simulation like OP's, lets us "guess" the answer's x,y are both multiples of 2016 and may be negative.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double f(int x, int y) {
double z = (x - y * sqrt(2016.0)) / (y + sqrt(2016.0));
z = z - 2016;
return z * z;
}
#define M 3000
int main() {
double best_diff = DBL_MAX;
int best_x = 0;
int best_y = 0;
int x, y;
for (x = -M; x < M; x++) {
for (y = -M; y < M; y++) {
double diff = f(x * 2016, y * 2016);
if (diff < best_diff) {
best_diff = diff;
best_x = x;
best_y = y;
}
if (diff == 0) {
printf("Numbers are: %d and %d.\n", best_x*2016, best_y*2016);
}
}
}
if (best_diff != 0.0) {
printf("Numbers are: %d and %d --> %e.", best_x*2016, best_y*2016, best_diff);
}
return 0;
}
Output
Numbers are: -4064256 and -2016.
The result from operations with floats are in general not exact.
Change:
if( (x - y * sqrt(2016.0)) / (y + sqrt(2016.0) ) == 2016)
to something like
if( fabs((x - y * sqrt(2016.0)) / (y + sqrt(2016.0) ) - 2016) < 0.00000001)
where 0.00000001 is a tolerance chosen by you.
But as pointed out, you don't want to search through the domains of more variables than necessary. Solve the math first. Using Wolfram Alpha like this we get y=(x-24192*√14)/(12*(168+√14))

How do I print the answer to an equation in C?

I'd like for the program to solve my equation yet sadly it doesn't. Additionally, I'd want for it to print an answer depending on the value of x that I input in the equation. Please let me know how I would be able to print the answer or how I can program it so that the equation gives me an answer that I can then print.
/* Preprocessor directives */
#include <stdio.h>
#include <math.h>
/* Main program */
void main ()
{
/*
variable declaration section comments
l: length value
q: value of q
ei: value of ei
s: l devided by 2 since 0 < x < l/2
b: the length l (thus, 20)
z: 0
first_equation: The first equation pertaining to 0 < x < l/2
second_equation:The second equation pertaining to l/2 < x < l
*/
double x, first_equation, second_equation, l, q, ei, s, b, z;
l = 20.0;
q = 4000.0;
ei = 1.2 * (pow(10.0, 8.0));
s = l / 2.0;
b = l;
z = 0.0;
printf ("please enter the x-value\n");
scanf ("%lf", &x);
/* Deflection equations */
first_equation = ((q * x) / (384.0 * ei)) * ((9 * (pow(l, 3.0))) - (24.0 * l * (pow(x, 2.0))) + (16 * (pow(x, 3.0))));
second_equation = ((q * l) / (384.0 * ei)) * ((8 * (pow(x, 3.0))) - (24.0 * l * (pow(x, 2.0))) + (17 * (pow(l, 2.0)) * x) - (pow(l, 3.0)));
/* Determining what equation to use */
if (x >= z && x <= s)
printf ("\n first_equation\n\n");
else if (x > s && x <= b)
printf ("\n second_equation\n\n", second_equation);
else if (x < 0 || x > b)
printf ("\n invalid location\n\n");
return;
}
This...
printf ("\n second_equation\n\n", second_equation);
... does not print the second_equation variable: it provides it as an argument to printf, but printf only uses extra arguments as directed by %f or other conversion instructions embedded in the text provided as the first argument. You could write:
printf ("\n second_equation %f\n\n", second_equation);
You may want to do something similar for first_equation.
Alternatively [when I answered the question was tagged C++] you could use C++ I/O routines (scanf and printf are from the C library, and have a number of disadvantages, the most obvious here being that you have to remember funny letter codes like "lf" matching your data types)...
#include <iostream>
...at the very top of your file, then in your function write...
std::cout << "\n second_equation " << second_equation << "\n\n";
You could also use C++ I/O for input, replacing scanf with...
if (!(std::cin >> x))
{
std::cerr << "you didn't enter a valid number\n";
exit(1);
}
Your code is really unclear; but going by your question, you seem to want to be able to print your answer. In that case, here is the proper syntax
printf ("Answer: %d \n", yourAnswer); //if 'yourAnswer' is decimal or number
To use one of your code snippets, you'll have this:
printf ("\n second_equation: %d\n", second_equation);

Resources