Read the Array of Numbers
In this step, you'll learn how to read an array of numbers in C, which is the first crucial step in determining the mode of a dataset. We'll create a C program that allows input of a set of numbers and prepares them for frequency analysis.
First, let's create a new C file for our mode calculation program:
cd ~/project
nano mode_calculation.c
Now, add the following code to the file:
#include <stdio.h>
#define MAX_SIZE 100
int main() {
int numbers[MAX_SIZE];
int n, i;
// Input 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]);
}
// Print the entered array to verify input
printf("Entered array: ");
for (i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
Compile and run the program:
gcc mode_calculation.c -o mode_calculation
./mode_calculation
Example output:
Enter the number of elements (max 100): 5
Enter 5 integers:
3 4 2 4 1
Entered array: 3 4 2 4 1
Let's break down the key parts of this code:
#define MAX_SIZE 100
sets a maximum limit for the array to prevent overflow.
scanf()
is used to input the number of elements and the array values.
- We print the array to verify that the input was correctly captured.
The code demonstrates basic array input in C, which is essential for our mode calculation process. In the next steps, we'll build upon this to count frequencies and determine the mode.