# Fibonacci series using while loop

Status
Not open for further replies.

#### zilch

##### Member level 2 Hi, I am trying to implement a Fibonacci series using while loop and written in C. Im not quite good in programming so im asking for help to check if there's something wrong in my code because i cant get the output that i want. I just want the output to start with 1, not 0 (the conventional one). For example, ill input 4; the output should be : 1 1 2 3.

//this is my code

Code:
#include <stdio.h>
int main()
{
int i;
int n;
int a=0;
int b=0;
int x;
printf("Input: ");
scanf("%d", &n);

while (i<=n)
{
if(i==1)
{
printf("Output: \n");
printf("1 ");
}
else if(i==2)
{
printf("1 ");
}
else
{
x = a + b;
a = b;
b = x;
i++;
printf(" %d ", x);
}
}
return 0;
}

#### andre_teprom

##### Super Moderator
Staff member You had not assigned any initial value to variable i.
To solve that, at line 1 replace int i by int i=1

In addition, you are returning the constant value 0.
Shouldn't you return i ?

#### zilch

##### Member level 2 You had not assigned any initial value to variable i.
To solve that, at line 1 replace int i by int i=1

In addition, you are returning the constant value 0.
Shouldn't you return i ?
I tried your suggestions, and i got an output of never ending 1. :???:

#### andre_teprom

##### Super Moderator
Staff member I made a wrong assumption, the return intruction above do not output the fibonacci value. I did not make an accurate analysis of your code, but it do not look so simple like the classic algorithm in pseudo code:

Code:
[B]function [/B]fib(n)
i = 1
j = 1
[B]for[/B] k=1 [B]to[/B] n [B]do[/B]
t = i + j
i = j
j = t
[B]return[/B] j

##### Super Moderator
Staff member The problem is because you are using a while loop instead of a for loop.

You have to explicitly increment i every time through the while loop, in this case you only do that if i is not 1 or 2

Option 1. either add i++ in each if and else if clause (it's missing from both the 1st and 2nd branches)
Option 2. just put the i++ at the start before the if statement and remove it every where else and change the initial value to int i=0.

andre the return is the OS return code saying the program completed without errors (Hmmm, doesn't seem to work ;-))

#### zilch

##### Member level 2 Hi guys, this problem is solved.The goal here is to make a subroutine (which i forgot to mention earlier ) for fibonacci sequence using loop.
Code:
#include <stdio.h>
void fibonacci (int n);

int main()
{
int n;
printf("Input: ");
scanf("%d", &n);
fibonacci(n);
}
void fibonacci(int n){
int i=1, a=0, b=1, x;

while(i<=n)
{
if (i==1){
x = i;
i++;
}
else{
x = a + b;
a = b;
b = x;
i++;
}
printf(" %d ", x);
}
}

Status
Not open for further replies.