Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <math.h>
- #include <time.h>
- #include <limits.h>
- // Define the maximum size our array can hold
- #define MAX_SIZE 100
- // Function declarations - these tell the compiler what functions we'll define later
- void print_menu(); // Shows the menu options to user
- int get_user_choice(); // Gets user's menu choice
- void clear_input_buffer(); // Clears leftover characters from input
- void handle_fill_with_random(int arr[], int* current_size); // Fills array with random numbers
- void handle_check_presence(const int arr[], int current_size); // Searches for a specific value
- void print_array(const int arr[], int current_size); // Displays all array elements
- void handle_find_closest_to_mean(const int arr[], int current_size); // Finds element closest to average
- void handle_load_from_file(int arr[], int* current_size); // Loads numbers from a file
- void handle_save_to_file(const int arr[], int current_size); // Saves numbers to a file
- int search_array(const int arr[], int size, int value_to_find); // Helper function to search array
- double calculate_mean(const int arr[], int size); // Helper function to calculate average
- int find_closest_to_value(const int arr[], int size, double target_value); // Helper function to find closest value
- /*
- * MAIN FUNCTION - This is where the program starts running
- * It creates an array, shows a menu, and handles user choices in a loop
- */
- int main() {
- // Create an array to store up to MAX_SIZE integers
- int array[MAX_SIZE];
- // Keep track of how many numbers are actually in the array (starts at 0 - empty)
- int current_size = 0;
- // Variable to store the user's menu choice
- int choice;
- // Initialize the random number generator with current time
- // This makes sure we get different random numbers each time we run the program
- srand(time(NULL));
- // Main program loop - keeps running until user chooses to exit
- while (1) {
- // Show the menu options to the user
- print_menu();
- // Get the user's choice from the menu
- choice = get_user_choice();
- // Use a switch statement to handle different menu choices
- switch (choice) {
- case 1:
- // Fill the array with random numbers
- handle_fill_with_random(array, ¤t_size);
- break;
- case 2:
- // Search for a specific number in the array
- handle_check_presence(array, current_size);
- break;
- case 3:
- // Show all numbers currently in the array
- print_array(array, current_size);
- break;
- case 4:
- // Find which number is closest to the average of all numbers
- handle_find_closest_to_mean(array, current_size);
- break;
- case 5:
- // Load numbers from a text file into the array
- handle_load_from_file(array, ¤t_size);
- break;
- case 6:
- // Save the current array numbers to a text file
- handle_save_to_file(array, current_size);
- break;
- case 7:
- // Exit the program
- printf("Exiting program. Goodbye!\n");
- return 0; // This ends the program
- default:
- // If user enters invalid choice, show error message
- printf("\n!!! Invalid choice. Please enter a number between 1 and 7. !!!\n");
- break;
- }
- // Pause and wait for user to press any key before showing menu again
- printf("\nPress any key to continue\n");
- getchar(); // This waits for the user to press Enter
- }
- return 0; // Program ends successfully
- }
- /*
- * This function displays the main menu with all available options
- * It doesn't take any parameters and doesn't return anything
- */
- void print_menu() {
- printf("========================================\n");
- printf(" Array Operations Menu \n");
- printf("========================================\n");
- printf("1. Fill array with random numbers\n");
- printf("2. Check for an element by value\n");
- printf("3. Print array contents\n");
- printf("4. Find element closest to the mean\n");
- printf("5. Load array from file\n");
- printf("6. Save array to file\n");
- printf("7. Exit\n");
- printf("----------------------------------------\n");
- }
- /*
- * This function asks the user to enter their menu choice and returns it
- * Returns: the number the user chose, or -1 if they entered invalid input
- */
- int get_user_choice() {
- int choice;
- printf("Enter your choice: ");
- // Try to read an integer from user input
- // scanf returns 1 if it successfully read one integer, 0 if it failed
- if (scanf("%d", &choice) != 1) {
- // If scanf failed (user didn't enter a number), clean up and return error
- clear_input_buffer();
- return -1;
- }
- // Clean up any leftover characters in the input buffer
- clear_input_buffer();
- return choice;
- }
- /*
- * CLEAR_INPUT_BUFFER FUNCTION
- * This function removes any leftover characters from the input buffer
- * This prevents problems when the user types extra characters
- */
- void clear_input_buffer() {
- int c;
- // Keep reading characters until we find a newline (\n) or end of file
- while ((c = getchar()) != '\n' && c != EOF);
- }
- /*
- * This function fills the array with random numbers
- * Parameters:
- * arr[] - the array to fill with numbers
- * current_size - pointer to the variable that tracks how many numbers are in the array
- */
- void handle_fill_with_random(int arr[], int* current_size) {
- int new_size;
- // Ask user how many random numbers they want
- printf("How many numbers would you like to generate? (1-%d): ", MAX_SIZE);
- // Try to read the number from user
- if (scanf("%d", &new_size) != 1) {
- printf("Invalid input. Please enter a number.\n");
- clear_input_buffer();
- return; // Exit this function early if input was invalid
- }
- clear_input_buffer();
- // Check if the requested size is valid (between 1 and MAX_SIZE)
- if (new_size <= 0 || new_size > MAX_SIZE) {
- printf("Invalid size. Please choose a number between 1 and %d.\n", MAX_SIZE);
- return; // Exit this function early if size is invalid
- }
- // Update the current size of the array
- *current_size = new_size;
- // Fill the array with random numbers
- for (int i = 0; i < *current_size; i++) {
- // Generate a random number between 0 and INT_MAX-1
- arr[i] = rand() % INT_MAX - 1;
- }
- // Tell the user we're done
- printf("%d random numbers have been generated and stored in the array.\n", *current_size);
- }
- /*
- * This function searches for a specific number in the array
- * Parameters:
- * arr[] - the array to search in
- * current_size - how many numbers are currently in the array
- */
- void handle_check_presence(const int arr[], int current_size) {
- // Check if the array is empty
- if (current_size == 0) {
- printf("The array is empty. There is nothing to search for.\n");
- return; // Exit early if array is empty
- }
- int value_to_find;
- printf("Enter the value to search for: ");
- // Try to read the number to search for
- if (scanf("%d", &value_to_find) != 1) {
- printf("Invalid input. Please enter a number.\n");
- clear_input_buffer();
- return;
- }
- clear_input_buffer();
- // Use our helper function to search for the value
- int index = search_array(arr, current_size, value_to_find);
- // Check if the value was found
- if (index != -1) {
- // -1 means "not found", so anything else means we found it
- printf("Value %d found at index %d.\n", value_to_find, index);
- } else {
- printf("Value %d was not found in the array.\n", value_to_find);
- }
- }
- /*
- * This function displays all the numbers currently in the array
- * Parameters:
- * arr[] - the array to display
- * current_size - how many numbers are in the array
- */
- void print_array(const int arr[], int current_size) {
- // Check if array is empty
- if (current_size == 0) {
- printf("The array is empty.\n");
- return;
- }
- // Print header showing how many elements we have
- printf("Array contents (%d elements):\n[ ", current_size);
- // Print each number in the array
- for (int i = 0; i < current_size; i++) {
- printf("%d ", arr[i]);
- }
- // Close the bracket to make it look nice
- printf("]\n");
- }
- /*
- * This function finds which number in the array is closest to the average (mean)
- * Parameters:
- * arr[] - the array to analyze
- * current_size - how many numbers are in the array
- */
- void handle_find_closest_to_mean(const int arr[], int current_size) {
- // Check if array is empty
- if (current_size == 0) {
- printf("The array is empty. Cannot calculate the mean.\n");
- return;
- }
- // Calculate the average of all numbers in the array
- double mean = calculate_mean(arr, current_size);
- // Find which number is closest to this average
- int closest_index = find_closest_to_value(arr, current_size, mean);
- // Show the results to the user
- printf("The arithmetic mean of the array is: %.2f\n", mean);
- printf("The element closest to the mean is %d at index %d.\n", arr[closest_index], closest_index);
- }
- /*
- * This function loads numbers from a text file into the array
- * Parameters:
- * arr[] - the array to fill with numbers from the file
- * current_size - pointer to update with how many numbers were loaded
- */
- void handle_load_from_file(int arr[], int* current_size) {
- char filename[100]; // Array to store the filename (up to 99 characters + null terminator)
- printf("Enter the filename to load from: ");
- scanf("%99s", filename); // Read filename, limit to 99 characters for safety
- clear_input_buffer();
- // Try to open the file for reading
- FILE* file = fopen(filename, "r"); // "r" means read mode
- if (file == NULL) {
- // If file couldn't be opened, print error message
- perror("Error opening file");
- return;
- }
- int count = 0;
- // Keep reading integers from the file until we reach MAX_SIZE or run out of numbers
- while (count < MAX_SIZE && fscanf(file, "%d", &arr[count]) == 1) {
- count++; // Successfully read a number, so increment counter
- }
- // Close the file when we're done
- fclose(file);
- // Update the array size with how many numbers we actually loaded
- *current_size = count;
- printf("Successfully loaded %d integers from '%s'.\n", *current_size, filename);
- }
- /*
- * This function saves all numbers from the array to a text file
- * Parameters:
- * arr[] - the array containing numbers to save
- * current_size - how many numbers are in the array
- */
- void handle_save_to_file(const int arr[], int current_size) {
- // Check if there's anything to save
- if (current_size == 0) {
- printf("The array is empty. Nothing to save.\n");
- return;
- }
- char filename[100]; // Array to store the filename
- printf("Enter the filename to save to: ");
- scanf("%99s", filename); // Read filename safely
- clear_input_buffer();
- // Try to open the file for writing
- FILE* file = fopen(filename, "w"); // "w" means write mode (creates new file or overwrites existing)
- if (file == NULL) {
- // If file couldn't be opened, print error message
- perror("Error opening file for writing");
- return;
- }
- // Write each number to the file, one per line
- for (int i = 0; i < current_size; i++) {
- fprintf(file, "%d\n", arr[i]); // Write number followed by newline
- }
- // Close the file when we're done
- fclose(file);
- printf("Successfully saved %d integers to '%s'.\n", current_size, filename);
- }
- /*
- * This function searches for a specific value in the array
- * Parameters:
- * arr[] - the array to search in
- * size - how many elements are in the array
- * value_to_find - the number we're looking for
- * Returns: the index where the value was found, or -1 if not found
- */
- int search_array(const int arr[], int size, int value_to_find) {
- // Check each element in the array
- for (int i = 0; i < size; i++) {
- if (arr[i] == value_to_find) {
- return i; // Found it! Return the index
- }
- }
- return -1; // Didn't find it, return -1 to indicate "not found"
- }
- /*
- * This function calculates the average (arithmetic mean) of all numbers in the array
- * Parameters:
- * arr[] - the array of numbers
- * size - how many numbers are in the array
- * Returns: the average as a decimal number
- */
- double calculate_mean(const int arr[], int size) {
- // If array is empty, return 0
- if (size == 0) {
- return 0.0;
- }
- // Use long long to avoid overflow when adding large numbers
- long long sum = 0;
- // Add up all the numbers
- for (int i = 0; i < size; i++) {
- sum += arr[i];
- }
- // Calculate and return the average
- // Cast to double to get decimal result instead of integer division
- return (double)sum / size;
- }
- /*
- * This function finds which element in the array is closest to a target value
- * Parameters:
- * arr[] - the array to search in
- * size - how many elements are in the array
- * target_value - the value we want to find the closest match to
- * Returns: the index of the element that's closest to the target value
- */
- int find_closest_to_value(const int arr[], int size, double target_value) {
- // Start by assuming the first element is closest
- int closest_index = 0;
- // Calculate how far the first element is from the target
- // fabs() gives us the absolute value (always positive distance)
- double min_difference = fabs((double)arr[0] - target_value);
- // Check all other elements to see if any are closer
- for (int i = 1; i < size; i++) {
- // Calculate distance from current element to target
- double current_difference = fabs((double)arr[i] - target_value);
- // If this element is closer than our current best, remember it
- if (current_difference < min_difference) {
- min_difference = current_difference;
- closest_index = i;
- }
- }
- return closest_index; // Return the index of the closest element
- }
Advertisement
Add Comment
Please, Sign In to add comment