0
#include<stdio.h>

int main() {

    int sum;
    int n,num1,num2;
    printf("Enter a number:");
    scanf_s("%d", &n);

    if (n >= 1)
        num1 = 1;
    if (n >= 2) {
        num2 = 1;
        sum = num1 + num2;
        printf("%d\n", sum);
    }
    int say = 2;
    while (say <= 10) {
        if (n >= 3) {
            sum = sum + n;
            printf("%d\n", sum);
            n++;
            say++;
        }
        if (say== 10)
            break;
    }
}

I couldn't find the error program is working like these while entering the input number for 10

2 
12 
23
35
48
62
77
93
110
dbush
  • 205,898
  • 23
  • 218
  • 273
  • input number for 10 –  Feb 20 '20 at 20:13
  • 5
    `sum = sum + n;` is not how you compute a Fibonacci sequence. You need to remember the most recent two members of the sequence. Then you add them to get the next member. Then you need to adjust your saved values of the “most recent two members” to accommodate the fact you have moved on to a new member. – Eric Postpischil Feb 20 '20 at 20:14

1 Answers1

3

This looks like something but not like the code that creates fibonacci sequence. look at this implementation.

#include <stdio.h>

unsigned long long a = 0;
unsigned long long b = 1;

for(int i = 0;i < 50; i++){
    unsigned long long old_b = b;
    b += a;
    a = old_b;
    printf("%llu\n", b);
}

fibonacci sequence is simply adding the previous value to the current value continuously. so you just have to keep track of the previous values.

fibonacci

masonCherry
  • 894
  • 6
  • 14
  • The largest number you can fit in a unsigned long long is 18446744073709551615 , so 12200160415121876738 is the last number of the golden ratio sequence you can fit, after that it's undefined behaviour. Your code overflows. – anastaciu Feb 20 '20 at 21:07
  • @anastaciu No UB here, just wrong F() after 12200160415121876738. Overflow well defined for `unsigned long long` – chux - Reinstate Monica Feb 20 '20 at 22:24
  • @chux-ReinstateMonica you are correct, unsigned overflow is well defined in both C and C++ standards, good catch. – anastaciu Feb 20 '20 at 22:53