ImpurestClub
ImpurestClub

Reputation: 303

C - Array sum function constantly returning zero

I'm trying to write a a program that lets the user generate anywhere from 1-75 Fibonacci numbers, print them, and then add all of those values together to get to over all sum. I had no problem generating the numbers and printing them, but for some reason I'm having a lot more trouble with the sum function. For some reason it only returns 0...and after staring at this for as many hours as I have I'm at a loss. Any and all help would be greatly appreciated. My code is below:

#include <stdio.h>
#include <stdlib.h>

//function to calculate fibonacci number 1-75 (user specified)
int fibonacci(int * array, int size)
{
    int i;
    unsigned long long int Fibonacci[size]; //generating the array to save the Fibonacci values

    Fibonacci[0] = 0; //by definition
    Fibonacci[1] = 1; //by definition

    for (i = 2; i < size; i++) {
        Fibonacci[i] = Fibonacci[i-2] + Fibonacci[i-1]; //equation to calculate the numbers
    }

    for (i = 0; i < size; i++) {
        printf("%llu\t", Fibonacci[i]); //printing out the numbers
    }

    printf("\n");
    return size;
}

int fibonacciSum(int * array, int size)
{
    int i;
    int sum = 0;

    for (i = 0; i < size; i++) {
        sum += array[i];
    }

    return sum;
}

int main(void)
{
    int size;

    printf("How many Fibonacci numbers do you want to generate (between 1 and 75)?\n");
    scanf("%i", &size);

    int * FibonacciNumbers = (int*) calloc(size,sizeof(int));

    if (size < 1 || size > 75) {
        printf("Bad number!");
        return 1;
    }

    fibonacci(FibonacciNumbers, size);
    printf("The sum of the Fibonacci numbers is: %d\n", fibonacciSum(FibonacciNumbers, size));

    return 0;

}

Upvotes: 1

Views: 683

Answers (3)

Deck
Deck

Reputation: 1979

If you rewrite function fibonacci as

int fibonacci(int * array, int size)
{
    int i;

    array[0] = 0; 
    array[1] = 1; 

    for (i = 2; i < size; i++) {
        array[i] = array[i-2] + array[i-1]; //equation to calculate the numbers
    }

    for (i = 0; i < size; i++) {
        printf("%d\t", array[i]); //printing out the numbers
    }

    printf("\n");
    return size;
}

Because your job on Fibonacci array doesn't affect on array which is stored in main and used in other functions.

Upvotes: 6

xd6_
xd6_

Reputation: 483

forgetting to assign ? just not sure why the first one returns anything.

size = fibonacci(FibonacciNumbers, size);

And you mixed up the parameter name inside the function.

Upvotes: 0

randomusername
randomusername

Reputation: 8087

The Fibbonacci array is only accessible from within the function. You need to store the numbers in another array.

Upvotes: 2

Related Questions