Compute the Interquartile Range (IQR) in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to compute the Interquartile Range (IQR) in C programming. The lab covers the steps to read and sort an array of numbers, find the positions of the first and third quartiles (Q1 and Q3), and then calculate the IQR as the difference between Q3 and Q1. By the end of this lab, you will have a solid understanding of how to perform this statistical analysis using C.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435160{{"`Compute the Interquartile Range (IQR) in C`"}} c/for_loop -.-> lab-435160{{"`Compute the Interquartile Range (IQR) in C`"}} c/arrays -.-> lab-435160{{"`Compute the Interquartile Range (IQR) in C`"}} c/math_functions -.-> lab-435160{{"`Compute the Interquartile Range (IQR) in C`"}} end

Read and Sort the Array

In this step, you will learn how to read an array of numbers and sort it in preparation for calculating the Interquartile Range (IQR). We'll use C programming to accomplish this task.

First, let's create a C source file for our IQR calculation:

cd ~/project
nano iqr_calculation.c

Now, let's write the initial code to read and sort an array:

#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

// Function to compare integers for qsort
int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

int main() {
    int numbers[MAX_SIZE];
    int n, i;

    // Read the number of elements
    printf("Enter the number of elements (max %d): ", MAX_SIZE);
    scanf("%d", &n);

    // Input array elements
    printf("Enter %d integers:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &numbers[i]);
    }

    // Sort the array
    qsort(numbers, n, sizeof(int), compare);

    // Print sorted array
    printf("Sorted array: ");
    for (i = 0; i < n; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

Compile the program:

gcc -o iqr_calculation iqr_calculation.c

Run the program and provide an example input:

./iqr_calculation

Example output:

Enter the number of elements (max 100): 6
Enter 6 integers:
45 22 14 65 97 72
Sorted array: 14 22 45 65 72 97

Let's break down the code:

  • We define a maximum array size of 100 elements
  • compare() function is used by qsort() to sort integers
  • We read the number of elements from user input
  • qsort() is used to sort the array in ascending order
  • The sorted array is then printed

Find Q1 and Q3 Positions and Compute IQR = Q3 - Q1

In this step, we'll modify the previous program to calculate the Interquartile Range (IQR) by finding Q1 and Q3 positions.

Open the previous source file:

cd ~/project
nano iqr_calculation.c

Update the code to calculate IQR:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MAX_SIZE 100

// Function to compare integers for qsort
int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

// Function to calculate Q1 and Q3
double calculateQuartile(int *arr, int n, double position) {
    int index = floor(position);
    double fraction = position - index;

    if (fraction == 0) {
        return arr[index - 1];
    } else {
        return arr[index - 1] * (1 - fraction) + arr[index] * fraction;
    }
}

int main() {
    int numbers[MAX_SIZE];
    int n, i;
    double q1, q3, iqr;

    // Read the number of elements
    printf("Enter the number of elements (max %d): ", MAX_SIZE);
    scanf("%d", &n);

    // Input array elements
    printf("Enter %d integers:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &numbers[i]);
    }

    // Sort the array
    qsort(numbers, n, sizeof(int), compare);

    // Calculate Q1 and Q3 positions
    double q1_pos = 0.25 * (n + 1);
    double q3_pos = 0.75 * (n + 1);

    // Calculate Q1 and Q3
    q1 = calculateQuartile(numbers, n, q1_pos);
    q3 = calculateQuartile(numbers, n, q3_pos);

    // Calculate IQR
    iqr = q3 - q1;

    // Print results
    printf("Sorted array: ");
    for (i = 0; i < n; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    printf("Q1: %.2f\n", q1);
    printf("Q3: %.2f\n", q3);
    printf("IQR: %.2f\n", iqr);

    return 0;
}

Compile the updated program:

gcc -o iqr_calculation iqr_calculation.c -lm

Run the program and provide an example input:

./iqr_calculation

Example output:

Enter the number of elements (max 100): 7
Enter 7 integers:
12 15 18 22 25 30 35
Sorted array: 12 15 18 22 25 30 35
Q1: 15.00
Q3: 30.00
IQR: 15.00

Key points in the code:

  • calculateQuartile() handles both even and odd-sized arrays
  • Q1 is calculated at the 25th percentile
  • Q3 is calculated at the 75th percentile
  • IQR is computed as Q3 - Q1
  • We use linear interpolation for non-integer positions

Print the IQR

In this final step, we'll focus on formatting and presenting the Interquartile Range (IQR) results in a clear and informative manner.

Open the previous source file:

cd ~/project
nano iqr_calculation.c

Update the code to enhance IQR output and add some descriptive text:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define MAX_SIZE 100

// Previous functions remain the same (compare and calculateQuartile)

int main() {
    int numbers[MAX_SIZE];
    int n, i;
    double q1, q3, iqr;

    // Clear screen for better presentation
    printf("\033[2J\033[1;1H");

    // Introduction to IQR
    printf("Interquartile Range (IQR) Calculator\n");
    printf("=====================================\n\n");

    // Read the number of elements
    printf("Enter the number of elements (max %d): ", MAX_SIZE);
    scanf("%d", &n);

    // Input array elements
    printf("Enter %d integers:\n", n);
    for (i = 0; i < n; i++) {
        scanf("%d", &numbers[i]);
    }

    // Sort the array
    qsort(numbers, n, sizeof(int), compare);

    // Calculate Q1 and Q3 positions
    double q1_pos = 0.25 * (n + 1);
    double q3_pos = 0.75 * (n + 1);

    // Calculate Q1 and Q3
    q1 = calculateQuartile(numbers, n, q1_pos);
    q3 = calculateQuartile(numbers, n, q3_pos);

    // Calculate IQR
    iqr = q3 - q1;

    // Detailed output
    printf("\nData Analysis Results\n");
    printf("--------------------\n");
    printf("Original Data Set: ");
    for (i = 0; i < n; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n\n");

    // Formatted IQR output
    printf("Quartile Analysis:\n");
    printf("1st Quartile (Q1): %.2f\n", q1);
    printf("3rd Quartile (Q3): %.2f\n", q3);
    printf("Interquartile Range (IQR): %.2f\n", iqr);

    // Interpretation of IQR
    printf("\nInterpretation:\n");
    printf("The IQR represents the spread of the middle 50%% of the data.\n");
    printf("A smaller IQR indicates more consistent data,\n");
    printf("while a larger IQR suggests more variability.\n");

    return 0;
}

Compile the updated program:

gcc -o iqr_calculation iqr_calculation.c -lm

Run the program and provide an example input:

./iqr_calculation

Example output:

Interquartile Range (IQR) Calculator
=====================================

Enter the number of elements (max 100): 7
Enter 7 integers:
12 15 18 22 25 30 35

Data Analysis Results
--------------------
Original Data Set: 12 15 18 22 25 30 35

Quartile Analysis:
1st Quartile (Q1): 15.00
3rd Quartile (Q3): 30.00
Interquartile Range (IQR): 15.00

Interpretation:
The IQR represents the spread of the middle 50% of the data.
A smaller IQR indicates more consistent data,
while a larger IQR suggests more variability.

Key improvements:

  • Added clear screen command for better presentation
  • Enhanced output formatting
  • Included an interpretation of IQR
  • Maintained previous calculation logic

Summary

In this lab, you first learned how to read and sort an array of numbers in C programming. You created a C source file, wrote the initial code to read the array elements and sort them using the qsort() function. You then printed the sorted array to verify the sorting process.

Next, you will modify the previous program to calculate the Interquartile Range (IQR) by finding the positions of the first quartile (Q1) and the third quartile (Q3), and then computing the IQR as Q3 - Q1. Finally, you will print the calculated IQR.

Other C Tutorials you may like