Home > OS >  Fibonacci number code with for-loop and if statement error
Fibonacci number code with for-loop and if statement error

Time:09-23

so i'm a beginner and trying to solve a small project about making fibonacci number. The code essentially is about typing n (the sequence) and it will show you what value of fibonacci number in that n-sequence. but of course the code went wrong, the code just stop until i type the n-sequence, and nothing being printed after that. Can anybody check my code pls?

#include <stdio.h>

int main(){
  int n;
  int seq[n];
  int i;

  printf("number of sequence for the fibonacci number that you want to find out (from 0)= ");
  scanf("%d", &n);

  for(i = 0; i <= n; i  ){
    if(i == 0){
      seq[i] = 0;
    }
    else if(i == 1){
      seq[i] = 1;
    }
    else if(i > 1){
    seq[i] = seq[i-1]   seq[i-2];
    }
  }
  if(i == n){
    printf("the value in sequence %d is %d", n, seq[n]);
  }

return 0;
}

CodePudding user response:

You need to declare the variable length array seq after you entered its size

For example

  int n;
  int i;

  printf("number of sequence for the fibonacci number that you want to find out (from 0)= ");
  scanf("%d", &n);

  int seq[n   1];

The size of the array is specified as n 1 because the user is asked to enter the fibonacci number starting from 0.

Also this for loop will be correct provided that the array has n 1 elements.

  for(i = 0; i <= n; i  ){

It is better to write it like

  for(i = 0; i < n   1; i  ){

And this if statement

  if(i == n){

does not make a sense. Just output the value of the array element seq[n].

CodePudding user response:

apparently, in the loop, you set the boarder as i<=n while the array seq[n] is with the size of n. So i must be less than n.

CodePudding user response:

  1. n is uninitialized. It contains a garbage value.
  2. Don't use scanf() for reading user input. It is very error-prone. Just try typing some string and see what happens. Better use fgets() in combination with sscanf().
  3. for(i = 0; i <= n; i ) should be for(i = 0; i = n; i )
int n;
char input[255];

printf("Number of sequence: ");
fgets(input, sizeof input, stdin);
input[strcspn(input, "\n")] = '\0';

if (sscanf(input, "%d", &n) != 1) {
    // Handle input error
}

int seq[n];
int i;
for (i = 0; i < n; i  ) {
    if (i == 0 || i == 1)
        seq[i] = i;
    else
        seq[i] = seq[i-1]   seq[i-2];
}

if(i == n)
    printf("the value in sequence %d is %d", n, seq[n-1]);
  • Related