## Friday, August 12, 2011

### Calculation of permutation and combination using using functions in C

This program is an example of using functions. It teaches you how to declare function, define it and call. Here functions for calculating factorial and permutation/combination is used. Once you see the code you will be able to understand following

• Function declaration, definition, calls.
• Use of switch statement in program.
• How to write structured program.
• How to make menu in C

The complete source code and output is given here…

Source Code

//calculation of permutation and combination using function in C#include<stdio.h>#include<conio.h>   //for getch() function//function declaration must be//written before main function,//function definition is optional//you can write befor or after mainint factorial(int n){    int fact = 1;    int i;    for(i = n; i > 0; i--){        fact = fact*i;    }    return fact;}int permutation(int n,int r){    int per;    per = factorial(n)/(factorial(n-r));    return per;}int combination(int n,int r){    int comb; //local variable    comb = factorial(n)/(factorial(n-r)*factorial(r));    return comb; //return statement}int main(){    int choice;    int n,r;    while(1){        printf("\n1. Permutation\n2. Combination\n3. Factorial\n");        printf("Choose option: ");        scanf("%d",&choice);        switch(choice){ //start of switch statement            case 1:                printf("Enter value of n,r: ");                scanf("%d%d",&n,&r);                //calculation of combination with function call                printf("Permutation P(%d,%d) = %d",n,r,permutation(n,r));                break;            case 2:                printf("Enter value of n,r: ");                scanf("%d%d",&n,&r);                printf("Combination C(%d,%d) = %d",n,r,combination(n,r));                break;            case 3:                printf("Enter value of n: ");                scanf("%d",&n);                printf("The factorial %d! = %d",n,factorial(n));                break;            default: //if user enter other than 1 or 2                printf("Invalid choice! Enter either 1 or 2");        } //end of switch statement        printf("\nWant another calculation?(y/n):");        if(getche()=='n')        break;    }    return 0;}//end of main

Output