# Thread: Need help with fibonacci sequence in c

1. ## Need help with fibonacci sequence in c

Below is my code. My problem is that when i run it, it asks me how many times i want to run, i input my number and hit enter.... and nothing else happens.

Code:
#include <stdio.h>

int main() {

int num1 = 0;
int num2 = 1;

int num_t = 0;
printf("Enter the number of times you want the Fibonacci sequence to be run: \n");
scanf("%d", &num_t);

int num_r = 0;

while(num_r <= num_t); {
printf("Here is the next number: %d ", num1);
printf("Here is the next number: %d ", num2);
num1 = num1 + num2;
num2 = num1 + num2;
num_r += 1;

}
return 0;

}

2. please PM me if you've replied with a possible fix

3. On line #21, that semicolon says to the compiler that your while statement ends there, without any instructions. That results in an infinite loop if you input a number >= 0. Yes, C is weird like that sometimes. Remove it.

4. thanks so much!

5. IT WORKED Thanks so much, I have been cracking my head open for weeks with this lol thanks so much

6. Here is an alternate version. For 32 bit signed integer, max input is 46.

Code:
#include <stdio.h>

int main() {
int num1 =  1;    /* fib(-1) */
int num2 = -1;    /* fib(-2) */
int num_r;
int num_t;
int temp;
printf("Enter the number of times you want the Fibonacci sequence to be run: \n");
scanf("%d", &num_t);
for(num_r = 0; num_r <= num_t; num_r += 1){
temp = num1;
num1 = num1 + num2;
num2 = temp;
printf("%d\n", num1);
}
return 0;
}
or

Code:
#include <stdio.h>

int main() {
int num1 =  1;    /* fib(-1) */
int num2 = -1;    /* fib(-2) */
int num_r;
int num_t;
printf("Enter the number of times you want the Fibonacci sequence to be run: \n");
scanf("%d", &num_t);
for(num_r = 0; num_r <= num_t; num_r += 1){
num1 = num1 + num2;
num2 = num1 - num2;
printf("%d\n", num1);
}
return 0;
}