This is a low-level question, but I'm just learning...
I am attempting to write a program (lotto.c) in C that essentially calculates chances of winning the lottery. It must include recursion, so that's what I've done. program code is below - the function simply runs the formula that comes up with the numbers in Pascal's triangle (if you've ever taken discrete math this might ring some bells).
The problem is that when I put numbers in at the prompt (say n= 4 and r = 2), I get the following error: LOTTO caused a stack fault in module LOTTO.EXE at 0187:00401150.
Compiler is the free Borland C Builder.
If answering this requires the identities for Pascal's triangle I can give them, but suffice it to say that when n or r is less than 1, the return should be 1.
not trying to get someone to write the code for me, just trying to figure out what I'm doing wrong and maybe get pointed in the right direction.
TIA
Rachel
#include <stdio.h>
#include <stdlib.h>
int C (int n, int r)
{
if (n <= 1) return 1;
else return C(n, n-r);
}
int main ()
{
int n, r;
do
{
printf("\n\nEnter n and r, or 0 to exit > "
scanf("%d", &n);
if (n == 0) continue;
scanf("%d", &r);
printf("The number of combinations of %d items taken %d at a time is %d", n, r, C(n, r) );
} while (n != 0);
return EXIT_SUCCESS;
}
I am attempting to write a program (lotto.c) in C that essentially calculates chances of winning the lottery. It must include recursion, so that's what I've done. program code is below - the function simply runs the formula that comes up with the numbers in Pascal's triangle (if you've ever taken discrete math this might ring some bells).
The problem is that when I put numbers in at the prompt (say n= 4 and r = 2), I get the following error: LOTTO caused a stack fault in module LOTTO.EXE at 0187:00401150.
Compiler is the free Borland C Builder.
If answering this requires the identities for Pascal's triangle I can give them, but suffice it to say that when n or r is less than 1, the return should be 1.
not trying to get someone to write the code for me, just trying to figure out what I'm doing wrong and maybe get pointed in the right direction.
TIA
Rachel
#include <stdio.h>
#include <stdlib.h>
int C (int n, int r)
{
if (n <= 1) return 1;
else return C(n, n-r);
}
int main ()
{
int n, r;
do
{
printf("\n\nEnter n and r, or 0 to exit > "
scanf("%d", &n);
if (n == 0) continue;
scanf("%d", &r);
printf("The number of combinations of %d items taken %d at a time is %d", n, r, C(n, r) );
} while (n != 0);
return EXIT_SUCCESS;
}