This gives first 15 of fibonacci sequence in C language, but I have to write each sequence manually, how do I make it increment the 2 variables instead of having endless amounts of variables? It was a lot easier in C and Python, not sure why I can't figure it out in C..
#include <stdio.h>
int i;
int main()
{
int var = 1;
int var1 = 1;
int var2 = var var1;
printf("%d\n", var2);
int var3 = var2 var1;
printf("%d\n", var3);
int var4 = var3 var2;
printf("%d\n", var4);
int var5 = var4 var3;
printf("%d\n", var5);
int var6 = var5 var4;
printf("%d\n", var6);
int var7 = var6 var5;
printf("%d\n", var7);
int var8 = var7 var6;
printf("%d\n", var8);
int var9 = var8 var7;
printf("%d\n", var9);
int var10 = var9 var8;
printf("%d\n", var10);
int var11 = var10 var9;
printf("%d\n", var11);
int var12 = var11 var10;
printf("%d\n", var12);
int var13 = var12 var11;
printf("%d\n", var13);
int var14 = var13 var12;
printf("%d\n", var14);
int var15 = var14 var13;
printf("%d\n", var15);
int var16 = var15 var14;
printf("%d\n", var16);
int var17 = var16 var15;
printf("%d\n", var17);
int var18 = var17 var16;
printf("%d\n", var18);
int var19 = var18 var17;
printf("%d\n", var19);
}
Output: 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765
CodePudding user response:
Your question lacks key details. It's my guess that you are looking for something like Python's (x,y)=(y,x y)
.
>>> prev=3
>>> next=8
>>> (prev,next)=(next,prev next)
>>> prev
8
>>> next
11
>>>
Well,
(prev,next)=(next,prev next)
is basically equivalent to
tmp1 = next
tmp2 = prev next
prev = tmp1
next = tmp2
We can swap the last two assignments without breaking anything.
tmp1 = next
tmp2 = prev next
next = tmp2
prev = tmp1
This can be simplified.
this = next
next = prev
prev = this
And that's exactly what you'd need to use here.
int n = 10;
if ( n > 0 ) {
int prev = 0;
printf( "%d\n", prev );
int next = 1;
for ( int i=1; i<n; i ) {
int this = next;
printf( "%d\n", this );
next = prev;
prev = this;
}
}
0
1
1
2
3
5
8
13
21
34
Demo on Compiler Explorer
Note that we can fudge the starting values (1,0 instead of 0,1) to simplify the logic.
int n = 10;
int prev = 1;
int next = 0;
for ( int i=1; i<n; i ) {
int this = next;
printf( "%d\n", this );
next = prev;
prev = this;
}
Demo on Compiler Explorer
CodePudding user response:
Nevermind here it is, It just took me a while to figure it out, sorry.
#include <stdio.h>
int var = 1;
int var1 = 2;
int main()
{
while (var<100)
{
var =var1;
var1 = var;
printf("%d\n", var);
}
}