I'm trying to write a c program that draws sine and cosine curves simultaneously by using '+' for sine and 'x' for cosine and '*' when the values of sine and cosine are equal. Here is the code:
#include<stdio.h>
#include<math.h> /* for sin(x) */
#define M_PI 3.14159265358979323846264338327950288
int main() {
double x;
int s_indent;
int c_indent;
for(x = -180.0; x <=180.0; x+=15.0) {
/* compute value */
s_indent = 10 + 10* sin(x/180 * M_PI);
c_indent = 10 + 10* cos(x/180 * M_PI);
if(c_indent == s_indent){
for(;s_indent;--s_indent) putchar(' ');
printf("*\n");
}
else{
for(; s_indent; --s_indent) putchar(' ');
printf("+\n");
/* plot x at position */
for(; c_indent; --c_indent) putchar(' ');
printf("x\n");
}
}
return 0;
}
but the problem with the code is that it produces the curves line by line. Like here:
And I want to make it on the same line like this one here:
Thoughts?
In the posted code, each symbol is printed in a separate line at the calculated position, but what you have to do is to determine the order of the symbols and print both in the same line.
Consier using a simple function like
void print_after_n_spaces(int n, const char* str)
{
while (n-- > 0)
putchar(' ');
printf("%s", str);
}
Also, add another branch and calculate the difference between the two positions:
for(int x = -180; x <= 180; x += 15)
{
double angle = x / 180.0 * M_PI;
int s_pos = 10.5 + 10.0 * sin(angle);
int c_pos = 10.5 + 10.0 * cos(angle);
// ^^^^ To "round" the values
if (c_pos > s_pos)
{
print_after_n_spaces(s_pos, "+");
// ^^^ Don't print the newline here
print_after_n_spaces(c_pos - s_pos - 1, "x\n");
// ^^^^^^^^^^^^^^^^^ Difference between the positions
}
else if (c_pos < s_pos)
{
// Here prints first the "x" (the cosine), then the "+"
}
else
{
// Here prints only "*"
}
}