2

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;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
imnotarobot
  • 59
  • 1
  • 4
  • 2
    `int seq[n];` ==> `int seq[200];` if you want at most 200 numbers. Remember `n` is unassigned at this time (and you probably want to avoid *VLA*s anyway). – pmg Sep 22 '21 at 16:13
  • 2
    You need to put `int seq[n];` *after* you read `n` from the user. – Barmar Sep 22 '21 at 16:14
  • the posted code results in the following message: *untitled.c:5:3: warning: ‘n’ is used uninitialized in this function [-Wuninitialized]* – user3629249 Sep 23 '21 at 14:21

3 Answers3

3

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

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.

0
  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().
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+1]; // Edited: n+1 because fib starts from 0 
int i;
for (i = 0; i < n+1; i++) {
    if (i == 0 || i == 1)
        seq[i] = i;
    else
        seq[i] = seq[i-1] + seq[i-2];
}
Zakk
  • 1,935
  • 1
  • 6
  • 17