Search code examples
cfactorial

C Program that takes pairs of numbers from a file, calculates newton(n,k), and writes answer to another file


I need a help with a program that takes pairs of numbers from a txt file, calculates the Newton coefficient (n! / (n! . (n-k)!)), and writes the answer (score) to the other txt file. For now I have this:

#include <stdio.h>

void factorial() {
    long l1, l2;
    long score = 1;
    for (int i = 1; i < l2; i++) {
        score = (score * (l1 - i + 1) / i);
    }
}

void read() {
    long l1, l2;
    long score = 1;
    FILE *file = fopen("pairs.txt", "r");
    FILE *file2 = fopen("sum.txt", "r");
    while (fscanf(file, "%ld%ld", &l1, &l2) == 2) {
        factorial();
        fprintf(file2, "%ld", score);
    }
    printf("Score is: %ld", score);
    fclose(file);
    fclose(file2);
}

int main() {
    read();
    return 1;
}

The problem is that when I start the program it shows me answer Score is: 1, and there is nothing in the file sum.txt.


Solution

  • There are multiple problems in your code:

    • You must pass arguments to the binomial function, return the result with the return statement and store the return value in the calling code.

    • Your function to compute the Newton binomial coefficients is incorrect.

    • You should open the output file sum.txt for writing with the "w" mode string.

    • You should check if fopen() succeeded at opening the files. As posted, your code probably fails to open the output file sum.txt that does not exist because it tries to open it for reading. Hence file2 is NULL and invoking fprintf with a null stream pointer has undefined behavior. This would explain the crash you observe.

    Here is a corrected version:

    #include <errno.h>
    #include <stdio.h>
    #include <string.h>
    
    long binomial(long n, long k) {
        long value = 1;
        if (k < n - k) {
            k = n - k;
        }
        for (long i = n; i > k; i--) {
            value *= i;
        }
        for (long i = k; i > 1; i++) {
            value /= i;
        }
        return value;
    }
    
    int read(void) {
        long n, k, score;
        FILE *file1, *file2;
    
        file = fopen("pairs.txt", "r");
        if (file == NULL) {
            fprintf(stderr, "error opening pairs.txt: %s\n", strerror(errno));
            return 1;
        }
        file2 = fopen("sum.txt", "w");
        if (file2 == NULL) {
            fprintf(stderr, "error opening sum.txt: %s\n", strerror(errno));
            fclose(file);
            return 1;
        }
        while (fscanf(file, "%ld%ld", &n, &k) == 2) {
            score = binomial(n, k);
            fprintf(file2, "%ld\n", score);
        }
        //printf("Score is: %ld\n", score);
        fclose(file);
        fclose(file2);
        return 0;
    }
    
    int main(void) {
        return read();
    }