Compute Permutations (nPr) in C

CCBeginner
Practice Now

Introduction

In this lab, we will learn how to compute permutations (nPr) in C programming. The lab covers the following steps:

First, we will read the input values for n and r, which are essential for computing permutations. We will use the scanf() function to get the input from the user and print the entered values to confirm the input.

Next, we will implement functions to calculate the factorial and the permutation (nPr) using the formula nPr = n! / (n-r)!. We will handle the case where r is greater than n and display an error message accordingly.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435151{{"`Compute Permutations (nPr) in C`"}} c/variables -.-> lab-435151{{"`Compute Permutations (nPr) in C`"}} c/user_input -.-> lab-435151{{"`Compute Permutations (nPr) in C`"}} c/math_functions -.-> lab-435151{{"`Compute Permutations (nPr) in C`"}} end

Read n and r

In this step, we will learn how to read input values for n and r, which are essential for computing permutations in C programming.

First, let's create a new C file to implement our permutation calculation program:

cd ~/project
nano permutations.c

Now, let's write the code to read input values:

#include <stdio.h>

int main() {
    int n, r;

    printf("Enter the total number of items (n): ");
    scanf("%d", &n);

    printf("Enter the number of items to be selected (r): ");
    scanf("%d", &r);

    printf("You entered: n = %d, r = %d\n", n, r);

    return 0;
}

Example output:

Enter the total number of items (n): 5
Enter the number of items to be selected (r): 3
You entered: n = 5, r = 3

Let's break down the code:

  • We use scanf() to read integer inputs from the user
  • %d is the format specifier for integers
  • &n and &r are memory addresses where the input values will be stored
  • We print the entered values to confirm input

Compile and run the program:

gcc permutations.c -o permutations
./permutations

Compute nPr = n!/(n-r)!

In this step, we will implement a function to calculate the permutation (nPr) by computing factorials.

Let's modify the previous permutations.c file to add factorial calculation and permutation computation:

cd ~/project
nano permutations.c

Now, let's update the code with factorial and permutation calculation functions:

#include <stdio.h>

// Function to calculate factorial
unsigned long long factorial(int num) {
    unsigned long long result = 1;
    for (int i = 1; i <= num; i++) {
        result *= i;
    }
    return result;
}

// Function to calculate permutation (nPr)
unsigned long long permutation(int n, int r) {
    // Check for invalid input
    if (r > n) {
        printf("Error: r cannot be greater than n\n");
        return 0;
    }

    // Calculate nPr using the formula: n! / (n-r)!
    return factorial(n) / factorial(n - r);
}

int main() {
    int n, r;

    printf("Enter the total number of items (n): ");
    scanf("%d", &n);

    printf("Enter the number of items to be selected (r): ");
    scanf("%d", &r);

    unsigned long long result = permutation(n, r);

    if (result > 0) {
        printf("Permutation (nPr) of %d items taken %d at a time is: %llu\n", n, r, result);
    }

    return 0;
}

Compile and run the program:

gcc permutations.c -o permutations
./permutations

Example output:

Enter the total number of items (n): 5
Enter the number of items to be selected (r): 3
Permutation (nPr) of 5 items taken 3 at a time is: 60

Key points about the implementation:

  • factorial() function calculates the factorial of a given number
  • permutation() function implements the nPr formula: n! / (n-r)!
  • We use unsigned long long to handle larger factorial values
  • Input validation checks if r is less than or equal to n

Print the Result

In this step, we will enhance our permutation calculation program by adding more detailed output and formatting options.

Let's modify the permutations.c file to improve result presentation:

cd ~/project
nano permutations.c

Update the code with improved result printing:

#include <stdio.h>

// Function to calculate factorial
unsigned long long factorial(int num) {
    unsigned long long result = 1;
    for (int i = 1; i <= num; i++) {
        result *= i;
    }
    return result;
}

// Function to calculate permutation (nPr)
unsigned long long permutation(int n, int r) {
    // Check for invalid input
    if (r > n) {
        printf("Error: r cannot be greater than n\n");
        return 0;
    }

    // Calculate nPr using the formula: n! / (n-r)!
    return factorial(n) / factorial(n - r);
}

// Function to print detailed permutation explanation
void printPermutationDetails(int n, int r, unsigned long long result) {
    printf("\n--- Permutation Calculation Details ---\n");
    printf("Total number of items (n): %d\n", n);
    printf("Number of items selected (r): %d\n", r);
    printf("Calculation: %d P %d = %d! / (%d - %d)!\n", n, r, n, n, r);
    printf("Result: %llu different arrangements possible\n", result);
    printf("----------------------------------------\n");
}

int main() {
    int n, r;

    printf("Permutation (nPr) Calculator\n");
    printf("Enter the total number of items (n): ");
    scanf("%d", &n);

    printf("Enter the number of items to be selected (r): ");
    scanf("%d", &r);

    unsigned long long result = permutation(n, r);

    if (result > 0) {
        printPermutationDetails(n, r, result);
    }

    return 0;
}

Compile and run the program:

gcc permutations.c -o permutations
./permutations

Example output:

Permutation (nPr) Calculator
Enter the total number of items (n): 5
Enter the number of items to be selected (r): 3

--- Permutation Calculation Details ---
Total number of items (n): 5
Number of items selected (r): 3
Calculation: 5 P 3 = 5! / (5 - 3)!
Result: 60 different arrangements possible
----------------------------------------

Key improvements:

  • Added a dedicated printPermutationDetails() function
  • Included more informative output about the calculation
  • Explained the permutation formula and result
  • Improved user interface with a title and detailed explanation

Summary

In this lab, we learned how to read input values for n and r, which are essential for computing permutations in C programming. We also implemented functions to calculate factorial and permutation (nPr) using the formula n! / (n-r)!.

The key learning points are the use of scanf() to read integer inputs, the implementation of factorial and permutation calculation functions, and the handling of invalid input where r is greater than n.

Other C Tutorials you may like