Home>

### fibonacci sequence in for statement

I want to write a Fibonacci sequence up to 100 with a for statement.

``````#include<stdio.h>
int main (void) {
unsigned short data [3];
int i;
data [0] = 0;
data [1] = 1;
printf ("% d \ n", data [0]);
printf ("% d \ n", data [1]);
for (i = 1;data [2]<100;i ++) {
data [2] = data [1] + data [0];
printf ("% d \ n", data [2]);
data [0] = data [1];
data [1] = data [2];
}
return 0;
}``````

If this is the case, more than 100 will be output. How can I improve it?

It's not an improvement of the question code, but since you can write such a code,

``````#include<stdio.h>
int main (void)
{
for (int a = 0, b = 1, c;a<= 100;c = a + b, a = b, b = c)
printf ("% d \ n", a);
}``````

Is it an improvement to have one printf?

Postscript
Would you think that the code in the question was improved if you wrote:

``````#include<stdio.h>
int main (void)
{
unsigned short data [3];
data [0] = 0;
data [1] = 1;
for (;data [0]<100;) {
printf ("% d \ n", data [0]);
data [2] = data [1] + data [0];
data [0] = data [1];
data [1] = data [2];
}
return 0;
}``````

I just rewrote a, b, c to data [0], data [1], data [2].

``````int main (void) {
unsigned short data [3];
int i;
data [0] = 0;
data [1] = 1;
data [2] = data [1] + data [0];
printf ("% d \ n", data [0]);
printf ("% d \ n", data [1]);
for (i = 1;data [2]<100;i ++) {
printf ("% d \ n", data [2]);
data [0] = data [1];
data [1] = data [2];
data [2] = data [1] + data [0];
}
return 0;
}``````

in a for loop`i`Because I don't use`i ++`There is no point in doing it, and I wrote an infinite loop with while and calculated it.`data [2]`If the value of is over 100, you can escape. "Up to 100 ~" is ambiguous.

``````#include<stdio.h>
int main (void) {
unsigned short data [3];
data [0] = 0;
data [1] = 1;
printf ("% d \ n", data [0]);
printf ("% d \ n", data [1]);
while (1) {
data [2] = data [1] + data [0];
if (data [2]>100) {
break;
}
printf ("% d \ n", data [2]);
data [0] = data [1];
data [1] = data [2];
}
return 0;
}``````

for (i = 1;data [2]<100;i ++) {

Nothing is assigned to data [2] and it is used here.
Local variables will have random values ​​as they are, so it is very unlikely that this for statement will be executed.

``for (i = 1;data [2]<100;i ++)``