0

I have written a program to calculate y values according to given x values for the function y = (sqrt(3+x^2))/(20x^2+sqrt(x)). Using two counters, one for x values [i], and one for y values [n]. My x values show up fine, however, the y values return zeroes. What would be the mistake here? Very appreciated.

    for (i = 0; i < 30; i++)
    {
        x[i] = 20 i * 2 + 3;
    }   

    for (n = 0; i < 30 && n < 50; i++, n++)
    {
        y[n] = (sqrt(3 + (pow(x[i], 2))))) / (20 * pow(x[i], 2) + sqrt(x[i]));
    }

    for (i = 0, n = 0; i < 30 && n < 50; i++, n++)
    printf("x %lf, y %lf", x[i], y[n]);

return 0;

}

soundsfierce
  • 45
  • 2
  • 9
  • You should use float constants like 2.0 vs 2 to preclude integer arithmetic in expressions. You don't need both i and n in the final loop. – stark Sep 27 '20 at 16:10

2 Answers2

1

You are continuing to use i, without re-initializing it to 0 after the first for loop. Because the value of i stays at the value of times, the second for loop never gets to run. But you rightly initialized it while printing the values of x, y in the final loop.

Change your second for loop to

for (i =0, n = 0; i < times && n < Ymax; i++, n++)
//   ^^^^^
{
    y[n] = 1 - (1 - (sqrt(4 - (pow(x[i], 2))))) / (40 * pow(x[i], 2) + sqrt(x[i]));
}
Inian
  • 80,270
  • 14
  • 142
  • 161
0

Add a "i=0" line the initializer part of your second for loop.

You should use C99 style for loop like this :

for (int i = 0; ...)

to avoid such errors.