Search code examples
cfor-loopfibonaccivariable-length-array

Fibonacci number code with for-loop and if statement error


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;
}

Solution

  • 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].