Calculate the Mean of a Dataset in C

CCBeginner
Practice Now

Introduction

In this lab, you will learn how to calculate the mean of a dataset in C programming. The lab covers the following steps:

  1. Reading an array of numbers from the user input.
  2. Computing the sum of the numbers and then calculating the mean by dividing the sum by the count of numbers.
  3. Printing the calculated mean.

The lab provides a step-by-step guide, including sample code, to help you understand the process of mean calculation in C. By the end of this lab, you will have the skills to analyze and summarize numerical data using C programming.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/FunctionsGroup(["`Functions`"]) c/UserInteractionGroup -.-> c/output("`Output`") c/BasicsGroup -.-> c/variables("`Variables`") c/CompoundTypesGroup -.-> c/arrays("`Arrays`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/FunctionsGroup -.-> c/function_declaration("`Function Declaration`") c/FunctionsGroup -.-> c/math_functions("`Math Functions`") subgraph Lab Skills c/output -.-> lab-435136{{"`Calculate the Mean of a Dataset in C`"}} c/variables -.-> lab-435136{{"`Calculate the Mean of a Dataset in C`"}} c/arrays -.-> lab-435136{{"`Calculate the Mean of a Dataset in C`"}} c/user_input -.-> lab-435136{{"`Calculate the Mean of a Dataset in C`"}} c/function_declaration -.-> lab-435136{{"`Calculate the Mean of a Dataset in C`"}} c/math_functions -.-> lab-435136{{"`Calculate the Mean of a Dataset in C`"}} end

Read an Array of Numbers

In this step, you will learn how to read an array of numbers in C programming. We'll create a simple program that allows users to input a set of numbers and store them in an array.

First, let's create a new C file in the ~/project directory:

cd ~/project
nano mean_calculation.c

Now, enter the following code:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int numbers[MAX_SIZE];
    int count;

    // Prompt user for the number of elements
    printf("Enter the number of elements (max %d): ", MAX_SIZE);
    scanf("%d", &count);

    // Input validation
    if (count <= 0 || count > MAX_SIZE) {
        printf("Invalid number of elements!\n");
        return 1;
    }

    // Read numbers into the array
    printf("Enter %d numbers:\n", count);
    for (int i = 0; i < count; i++) {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &numbers[i]);
    }

    // Print the entered numbers
    printf("\nEntered numbers are:\n");
    for (int i = 0; i < count; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    return 0;
}

Compile the program:

gcc mean_calculation.c -o mean_calculation

Run the program:

./mean_calculation

Example output:

Enter the number of elements (max 100): 5
Enter 5 numbers:
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Enter number 5: 50

Entered numbers are:
10 20 30 40 50

Let's break down the key parts of the code:

  • #define MAX_SIZE 100 sets a maximum limit for the array size
  • scanf() is used to read the number of elements and individual numbers
  • We validate the input to ensure it's within the allowed range
  • A for loop is used to input and then display the numbers

This program demonstrates how to:

  1. Declare an array with a maximum size
  2. Get the number of elements from the user
  3. Input numbers into the array
  4. Validate user input
  5. Display the entered numbers

Compute Sum and then Mean = Sum/Count

In this step, we'll extend the previous program to calculate the sum and mean of the numbers entered by the user.

Open the existing file:

cd ~/project
nano mean_calculation.c

Modify the code to include sum and mean calculation:

#include <stdio.h>

#define MAX_SIZE 100

int main() {
    int numbers[MAX_SIZE];
    int count;
    int sum = 0;
    float mean;

    // Prompt user for the number of elements
    printf("Enter the number of elements (max %d): ", MAX_SIZE);
    scanf("%d", &count);

    // Input validation
    if (count <= 0 || count > MAX_SIZE) {
        printf("Invalid number of elements!\n");
        return 1;
    }

    // Read numbers into the array and calculate sum
    printf("Enter %d numbers:\n", count);
    for (int i = 0; i < count; i++) {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &numbers[i]);
        sum += numbers[i];
    }

    // Calculate mean
    mean = (float)sum / count;

    // Print the results
    printf("\nEntered numbers are:\n");
    for (int i = 0; i < count; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    printf("Sum of numbers: %d\n", sum);
    printf("Mean of numbers: %.2f\n", mean);

    return 0;
}

Compile the program:

gcc mean_calculation.c -o mean_calculation

Run the program:

./mean_calculation

Example output:

Enter the number of elements (max 100): 5
Enter 5 numbers:
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40
Enter number 5: 50

Entered numbers are:
10 20 30 40 50
Sum of numbers: 150
Mean of numbers: 30.00

Key changes in this version:

  • Added sum variable to track the total of all numbers
  • Integrated sum calculation into the input loop
  • Calculated mean by dividing sum by count
  • Used type casting (float) to ensure floating-point division
  • Added output for sum and mean with formatted printing

The program now demonstrates:

  1. Calculating the sum of array elements
  2. Computing the arithmetic mean
  3. Displaying results with precision

Print the Mean

In this final step, we'll refactor the code to create a function for calculating and printing the mean, making our program more modular and readable.

Open the existing file:

cd ~/project
nano mean_calculation.c

Update the code with a dedicated function for mean calculation:

#include <stdio.h>

#define MAX_SIZE 100

// Function to calculate and print mean
void calculateMean(int numbers[], int count) {
    if (count <= 0) {
        printf("Error: No numbers to calculate mean.\n");
        return;
    }

    int sum = 0;
    float mean;

    // Calculate sum
    for (int i = 0; i < count; i++) {
        sum += numbers[i];
    }

    // Calculate mean
    mean = (float)sum / count;

    // Print detailed statistics
    printf("\nStatistics:\n");
    printf("Number of elements: %d\n", count);
    printf("Sum of numbers: %d\n", sum);
    printf("Mean of numbers: %.2f\n", mean);
}

int main() {
    int numbers[MAX_SIZE];
    int count;

    // Prompt user for the number of elements
    printf("Enter the number of elements (max %d): ", MAX_SIZE);
    scanf("%d", &count);

    // Input validation
    if (count <= 0 || count > MAX_SIZE) {
        printf("Invalid number of elements!\n");
        return 1;
    }

    // Read numbers into the array
    printf("Enter %d numbers:\n", count);
    for (int i = 0; i < count; i++) {
        printf("Enter number %d: ", i + 1);
        scanf("%d", &numbers[i]);
    }

    // Print the entered numbers
    printf("\nEntered numbers are:\n");
    for (int i = 0; i < count; i++) {
        printf("%d ", numbers[i]);
    }
    printf("\n");

    // Calculate and print mean
    calculateMean(numbers, count);

    return 0;
}

Compile the program:

gcc mean_calculation.c -o mean_calculation

Run the program:

./mean_calculation

Example output:

Enter the number of elements (max 100): 4
Enter 4 numbers:
Enter number 1: 10
Enter number 2: 20
Enter number 3: 30
Enter number 4: 40

Entered numbers are:
10 20 30 40
Statistics:
Number of elements: 4
Sum of numbers: 100
Mean of numbers: 25.00

Key improvements in this version:

  • Created a separate calculateMean() function
  • Added more detailed statistical output
  • Improved error handling for edge cases
  • Maintained the same core functionality as previous steps
  • Made the code more modular and easier to read

The program demonstrates:

  1. Function-based approach to calculations
  2. Comprehensive statistical output
  3. Modular code design

Summary

In this lab, you will learn how to read an array of numbers in C programming, compute the sum and mean of the dataset, and then print the mean. First, you will prompt the user to enter a set of numbers and store them in an array. Then, you will calculate the sum of the numbers and divide it by the count to find the mean. Finally, you will print the calculated mean.

The key steps covered in this lab include declaring an array with a maximum size, getting the number of elements from the user, inputting numbers into the array, validating user input, and displaying the entered numbers. By the end of the lab, you will have a clear understanding of how to calculate the mean of a dataset in C programming.

Other C Tutorials you may like