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 ;
int i;
data  = 0;
data  = 1;
printf ("% d \ n", data );
printf ("% d \ n", data );
for (i = 1;data <100;i ++) {
data  = data  + data ;
printf ("% d \ n", data );
data  = data ;
data  = data ;
}
return 0;
}``````

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

• Answer # 1

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 ;
data  = 0;
data  = 1;
for (;data <100;) {
printf ("% d \ n", data );
data  = data  + data ;
data  = data ;
data  = data ;
}
return 0;
}``````

I just rewrote a, b, c to data , data , data .

• Answer # 2

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

• Answer # 3

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 `If the value of is over 100, you can escape. "Up to 100 ~" is ambiguous.

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

• Answer # 4

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

Nothing is assigned to data  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.

• Answer # 5

Others have answered about the correct program, so I will explain why more than 100 are output.
https://docs.microsoft.com/ja-jp/cpp/c-language/for-statement-c?view=vs-2019
As you can see here, this time

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

The second of them will continue to run as long as data  is less than 100. 144 is displayed
This is because data  = 89 is still set at this time.
Since it is calculated after outputting the answer of the correct program, the value of data  becomes 144 after outputting 89, and the for statement will not be executed next time.
By the way, data  is not initialized, so it may not work properly. Initialize data  before the for statement.