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?
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%-10sinstead.