Find the Range of a Dataset in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to find the range of a dataset in C programming. The lab covers the following steps: 1) Read and sort the array, 2) Calculate the range by finding the difference between the maximum and minimum values, and 3) Print the range. The lab provides a step-by-step guide with sample code to help you understand the process of analyzing statistical properties of a dataset 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-435185{{"`Find the Range of a Dataset in C`"}} c/for_loop -.-> lab-435185{{"`Find the Range of a Dataset in C`"}} c/arrays -.-> lab-435185{{"`Find the Range of a Dataset in C`"}} c/math_functions -.-> lab-435185{{"`Find the Range of a Dataset in C`"}} end

Read and Sort the Array

In this step, you'll learn how to read an array of numbers and sort it to prepare for calculating the range. We'll use a simple approach to input and organize the dataset.

First, let's create a C program to read and sort an array:

#include <stdio.h>

#define MAX_SIZE 100

// Function to swap two elements
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Bubble sort function to sort the array
void sortArray(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(&arr[j], &arr[j + 1]);
            }
        }
    }
}

int main() {
    int numbers[MAX_SIZE];
    int 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 (int i = 0; i < n; i++) {
        scanf("%d", &numbers[i]);
    }

    // Sort the array
    sortArray(numbers, n);

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

    return 0;
}

Let's break down the key components:

  1. We define a maximum array size of 100 elements.
  2. The swap() function helps exchange two array elements.
  3. sortArray() uses bubble sort to arrange elements in ascending order.
  4. In main(), we:
    • Read the number of elements
    • Input the array elements
    • Sort the array
    • Print the sorted array

Example compilation and execution:

gcc -o array_sort array_sort.c
./array_sort

Example output:

Enter the number of elements (max 100): 5
Enter 5 integers:
42 15 7 23 11
Sorted array: 7 11 15 23 42

Range = Max - Min

In this step, you'll learn how to calculate the range of a dataset by finding the difference between the maximum and minimum values in the sorted array.

Let's modify the previous program to calculate the range:

#include <stdio.h>

#define MAX_SIZE 100

// Function to swap two elements
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Bubble sort function to sort the array
void sortArray(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(&arr[j], &arr[j + 1]);
            }
        }
    }
}

// Function to calculate the range
int calculateRange(int arr[], int size) {
    // If array is empty, return 0
    if (size == 0) return 0;

    // Range is the difference between last (max) and first (min) elements
    return arr[size - 1] - arr[0];
}

int main() {
    int numbers[MAX_SIZE];
    int 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 (int i = 0; i < n; i++) {
        scanf("%d", &numbers[i]);
    }

    // Sort the array
    sortArray(numbers, n);

    // Calculate and print the range
    int range = calculateRange(numbers, n);

    printf("Minimum value: %d\n", numbers[0]);
    printf("Maximum value: %d\n", numbers[n - 1]);
    printf("Range: %d\n", range);

    return 0;
}

Key modifications in this step:

  1. Added calculateRange() function to compute the range
  2. The range is calculated by subtracting the first (minimum) element from the last (maximum) element in the sorted array
  3. Added print statements to show minimum, maximum, and range values

Example compilation and execution:

gcc -o range_calculator range_calculator.c
./range_calculator

Example output:

Enter the number of elements (max 100): 5
Enter 5 integers:
42 15 7 23 11
Minimum value: 7
Maximum value: 42
Range: 35

The range represents the spread of the dataset, calculated by subtracting the smallest value from the largest value in the sorted array.

Print the Range

In this final step, you'll learn how to format and display the range calculation results in a user-friendly manner, adding some statistical context to the output.

Let's create an enhanced version of our range calculation program:

#include <stdio.h>

#define MAX_SIZE 100

// Function to swap two elements
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Bubble sort function to sort the array
void sortArray(int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        for (int j = 0; j < size - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                swap(&arr[j], &arr[j + 1]);
            }
        }
    }
}

// Function to calculate the range
int calculateRange(int arr[], int size) {
    // If array is empty, return 0
    if (size == 0) return 0;

    // Range is the difference between last (max) and first (min) elements
    return arr[size - 1] - arr[0];
}

// Function to print detailed range information
void printRangeAnalysis(int arr[], int size, int range) {
    printf("\n--- Statistical Range Analysis ---\n");
    printf("Dataset Size: %d\n", size);
    printf("Minimum Value: %d\n", arr[0]);
    printf("Maximum Value: %d\n", arr[size - 1]);
    printf("Range: %d\n", range);

    // Additional insights
    printf("\nInterpretation:\n");
    printf("The range represents the spread of values in the dataset.\n");
    printf("A larger range indicates more variability in the data.\n");
}

int main() {
    int numbers[MAX_SIZE];
    int 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 (int i = 0; i < n; i++) {
        scanf("%d", &numbers[i]);
    }

    // Sort the array
    sortArray(numbers, n);

    // Calculate the range
    int range = calculateRange(numbers, n);

    // Print detailed range analysis
    printRangeAnalysis(numbers, n, range);

    return 0;
}

Key improvements in this step:

  1. Added printRangeAnalysis() function to provide a comprehensive output
  2. Included additional context about the range and data variability
  3. Formatted the output to be more informative and readable

Example compilation and execution:

gcc -o range_analysis range_analysis.c
./range_analysis

Example output:

Enter the number of elements (max 100): 6
Enter 6 integers:
10 25 7 42 15 33

--- Statistical Range Analysis ---
Dataset Size: 6
Minimum Value: 7
Maximum Value: 42
Range: 35

Interpretation:
The range represents the spread of values in the dataset.
A larger range indicates more variability in the data.

The program now provides a more comprehensive view of the dataset's range, helping users understand the statistical significance of the calculation.

Summary

In this lab, you first learned how to read and sort an array of numbers using a simple bubble sort algorithm. This step prepared the dataset for calculating the range. Next, you will learn how to find the range of the dataset by subtracting the minimum value from the maximum value in the sorted array. Finally, you will print the calculated range. The key learning points from the completed steps are reading and sorting an array, as well as the concept of the range of a dataset.

Other C Tutorials you may like