nChoosek

This is a program that prompts the user to enter a "n" value and a "k" value, and return how many different ways one can choose a value k from a distinct group n.

My code crashes and I don't see why.

Any help with a solution would be great thanks.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int n_choose_k(int n, int k);

int factorial(int m);

int main(int argc, char *argv[]){

    int input_n;

    int input_k;

    printf("Enter your 'n' & 'k' values:");

    scanf("%d\n", input_n);

    scanf("%d\n", input_k);

    printf("nCk = %d", n_choose_k(input_n, input_k));

    return 0;

}

int n_choose_k(int n, int k){

    int resnCk;

    resnCk = factorial(n)/(factorial((n-k))*(factorial(k)));

    return resnCk;
}




int factorial(int m){

    int result=m;

    int i;

    for(i=0;i<m;i++){

        result *= (result-1);

    }

    return result;

}
I think your problem is in lines 5 and 7.
First, that's not how you declare a function. Second, you don't need to there, those function are already defined. (lines 27 - 49)

Just erase lines 5 and 7, for reals, and see if it doesn't at least compile then.
If ya still have an issue I would move the main function to line 50, after the factorial function. It will still run first.
There is nothing wrong with how the functions are declared.

You should pass pointers to scanf.
1
2
scanf("%d\n", &input_n);
scanf("%d\n", &input_k);

Thank you both, all good now.
Topic archived. No new replies allowed.