Reputation: 145
As a simple attempt at a coding exercise in a book I've been reading, I wrote the following code:
#include <stdio.h>
int main() {
double data[12][5];
int i;
double t = 2.0;
for(i = 0; i < 12; i++) {
data[i][0] = t;
t += 0.1;
}
for(i = 0; i < 12; i++) {
data[i][1] = 1.0 / data[i][0];
data[i][2] = data[i][0] * data[i][0];
data[i][3] = data[i][2] * data[i][0];
data[i][4] = data[i][3] * data[i][0];
}
printf("x 1/x x^2 x^3 x^4\n");
int row;
int column;
for(row = 0; row < 12; row++) {
printf("%10lf %10lf %10lf %10lf %10lf\n", data[i][0], data[i][1], data[i][2], data[i][3], data[i][4]);
}
return 0;
}
However, when I run it the output appears as at ideone.com: http://ideone.com/KLWtdk. According to how I think the code should run, the far left column should be a range of values inclusive from 2.0 to 3.0 with a 0.1 step size. This is not the case, however.
Also, while chatting on IRC, I was told to not use tabs when printing tables of data but instead to use printf widths. I want to be able to have a header over each column in text, however - is there any way to do that?
Upvotes: 2
Views: 96
Reputation: 484
In the last loop you use different variable for iteration and different for printing values. variable i
used for declaration,condition check & increments/decrements.
i is that variable.
Another variable row
used for printing values which have garbage value and not changed throughout the loop.
row is that variable
Upvotes: 0
Reputation: 21757
Your problem is that you declare iteration variable row
, but use i
for index in the print statement. Since the value of i
is independent of the value of row
, every iteration will give you the same values, and they won't be the right ones.
You can resolve this by accessing the array elements as data[row][column_index]
e.g. data[row][0]
Regarding the formatting, as mentioned by @JonathanLeffler:
The way to get the labels aligned is
printf("%10s %10s %10s %10s %10s\n", "x", "1/x", "x^2", "x^3", "x^4");
Use the same width in the string formats as in the numeric formats. This right justifies the labels; to left justify, use %-10s
instead.
Upvotes: 4
Reputation: 1577
Use data[row][0], data[row][1], data[row][2], data[row][3]
while printing results.
Upvotes: -1