Suzana_Marek

HW_Martin

Jul 10th, 2025
376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 14.67 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4. #include <time.h>
  5. #include <limits.h>
  6.  
  7.  
  8. // Define the maximum size our array can hold
  9. #define MAX_SIZE 100
  10.  
  11. // Function declarations - these tell the compiler what functions we'll define later
  12. void print_menu();                                          // Shows the menu options to user
  13. int get_user_choice();                                      // Gets user's menu choice
  14. void clear_input_buffer();                                  // Clears leftover characters from input
  15.  
  16. void handle_fill_with_random(int arr[], int* current_size); // Fills array with random numbers
  17. void handle_check_presence(const int arr[], int current_size); // Searches for a specific value
  18. void print_array(const int arr[], int current_size);       // Displays all array elements
  19. void handle_find_closest_to_mean(const int arr[], int current_size); // Finds element closest to average
  20. void handle_load_from_file(int arr[], int* current_size);   // Loads numbers from a file
  21. void handle_save_to_file(const int arr[], int current_size); // Saves numbers to a file
  22.  
  23. int search_array(const int arr[], int size, int value_to_find); // Helper function to search array
  24. double calculate_mean(const int arr[], int size);           // Helper function to calculate average
  25. int find_closest_to_value(const int arr[], int size, double target_value); // Helper function to find closest value
  26.  
  27. /*
  28.  * MAIN FUNCTION - This is where the program starts running
  29.  * It creates an array, shows a menu, and handles user choices in a loop
  30.  */
  31. int main() {
  32.     // Create an array to store up to MAX_SIZE integers
  33.     int array[MAX_SIZE];
  34.  
  35.     // Keep track of how many numbers are actually in the array (starts at 0 - empty)
  36.     int current_size = 0;
  37.  
  38.     // Variable to store the user's menu choice
  39.     int choice;
  40.  
  41.     // Initialize the random number generator with current time
  42.     // This makes sure we get different random numbers each time we run the program
  43.     srand(time(NULL));
  44.  
  45.     // Main program loop - keeps running until user chooses to exit
  46.     while (1) {
  47.         // Show the menu options to the user
  48.         print_menu();
  49.  
  50.         // Get the user's choice from the menu
  51.         choice = get_user_choice();
  52.  
  53.         // Use a switch statement to handle different menu choices
  54.         switch (choice) {
  55.             case 1:
  56.                 // Fill the array with random numbers
  57.                 handle_fill_with_random(array, &current_size);
  58.                 break;
  59.             case 2:
  60.                 // Search for a specific number in the array
  61.                 handle_check_presence(array, current_size);
  62.                 break;
  63.             case 3:
  64.                 // Show all numbers currently in the array
  65.                 print_array(array, current_size);
  66.                 break;
  67.             case 4:
  68.                 // Find which number is closest to the average of all numbers
  69.                 handle_find_closest_to_mean(array, current_size);
  70.                 break;
  71.             case 5:
  72.                 // Load numbers from a text file into the array
  73.                 handle_load_from_file(array, &current_size);
  74.                 break;
  75.             case 6:
  76.                 // Save the current array numbers to a text file
  77.                 handle_save_to_file(array, current_size);
  78.                 break;
  79.             case 7:
  80.                 // Exit the program
  81.                 printf("Exiting program. Goodbye!\n");
  82.                 return 0; // This ends the program
  83.             default:
  84.                 // If user enters invalid choice, show error message
  85.                 printf("\n!!! Invalid choice. Please enter a number between 1 and 7. !!!\n");
  86.                 break;
  87.         }
  88.  
  89.         // Pause and wait for user to press any key before showing menu again
  90.         printf("\nPress any key to continue\n");
  91.         getchar(); // This waits for the user to press Enter
  92.     }
  93.  
  94.     return 0; // Program ends successfully
  95. }
  96.  
  97. /*
  98.  * This function displays the main menu with all available options
  99.  * It doesn't take any parameters and doesn't return anything
  100.  */
  101. void print_menu() {
  102.     printf("========================================\n");
  103.     printf("           Array Operations Menu        \n");
  104.     printf("========================================\n");
  105.     printf("1. Fill array with random numbers\n");
  106.     printf("2. Check for an element by value\n");
  107.     printf("3. Print array contents\n");
  108.     printf("4. Find element closest to the mean\n");
  109.     printf("5. Load array from file\n");
  110.     printf("6. Save array to file\n");
  111.     printf("7. Exit\n");
  112.     printf("----------------------------------------\n");
  113. }
  114.  
  115. /*
  116.  * This function asks the user to enter their menu choice and returns it
  117.  * Returns: the number the user chose, or -1 if they entered invalid input
  118.  */
  119. int get_user_choice() {
  120.     int choice;
  121.     printf("Enter your choice: ");
  122.  
  123.     // Try to read an integer from user input
  124.     // scanf returns 1 if it successfully read one integer, 0 if it failed
  125.     if (scanf("%d", &choice) != 1) {
  126.         // If scanf failed (user didn't enter a number), clean up and return error
  127.         clear_input_buffer();
  128.         return -1;
  129.     }
  130.  
  131.     // Clean up any leftover characters in the input buffer
  132.     clear_input_buffer();
  133.     return choice;
  134. }
  135.  
  136. /*
  137.  * CLEAR_INPUT_BUFFER FUNCTION
  138.  * This function removes any leftover characters from the input buffer
  139.  * This prevents problems when the user types extra characters
  140.  */
  141. void clear_input_buffer() {
  142.     int c;
  143.     // Keep reading characters until we find a newline (\n) or end of file
  144.     while ((c = getchar()) != '\n' && c != EOF);
  145. }
  146.  
  147. /*
  148.  * This function fills the array with random numbers
  149.  * Parameters:
  150.  *   arr[] - the array to fill with numbers
  151.  *   current_size - pointer to the variable that tracks how many numbers are in the array
  152.  */
  153. void handle_fill_with_random(int arr[], int* current_size) {
  154.     int new_size;
  155.  
  156.     // Ask user how many random numbers they want
  157.     printf("How many numbers would you like to generate? (1-%d): ", MAX_SIZE);
  158.  
  159.     // Try to read the number from user
  160.     if (scanf("%d", &new_size) != 1) {
  161.         printf("Invalid input. Please enter a number.\n");
  162.         clear_input_buffer();
  163.         return; // Exit this function early if input was invalid
  164.     }
  165.     clear_input_buffer();
  166.  
  167.     // Check if the requested size is valid (between 1 and MAX_SIZE)
  168.     if (new_size <= 0 || new_size > MAX_SIZE) {
  169.         printf("Invalid size. Please choose a number between 1 and %d.\n", MAX_SIZE);
  170.         return; // Exit this function early if size is invalid
  171.     }
  172.  
  173.     // Update the current size of the array
  174.     *current_size = new_size;
  175.  
  176.     // Fill the array with random numbers
  177.     for (int i = 0; i < *current_size; i++) {
  178.         // Generate a random number between 0 and INT_MAX-1
  179.         arr[i] = rand() % INT_MAX - 1;
  180.     }
  181.  
  182.     // Tell the user we're done
  183.     printf("%d random numbers have been generated and stored in the array.\n", *current_size);
  184. }
  185.  
  186. /*
  187.  * This function searches for a specific number in the array
  188.  * Parameters:
  189.  *   arr[] - the array to search in
  190.  *   current_size - how many numbers are currently in the array
  191.  */
  192. void handle_check_presence(const int arr[], int current_size) {
  193.     // Check if the array is empty
  194.     if (current_size == 0) {
  195.         printf("The array is empty. There is nothing to search for.\n");
  196.         return; // Exit early if array is empty
  197.     }
  198.  
  199.     int value_to_find;
  200.     printf("Enter the value to search for: ");
  201.  
  202.     // Try to read the number to search for
  203.     if (scanf("%d", &value_to_find) != 1) {
  204.         printf("Invalid input. Please enter a number.\n");
  205.         clear_input_buffer();
  206.         return;
  207.     }
  208.     clear_input_buffer();
  209.  
  210.     // Use our helper function to search for the value
  211.     int index = search_array(arr, current_size, value_to_find);
  212.  
  213.     // Check if the value was found
  214.     if (index != -1) {
  215.         // -1 means "not found", so anything else means we found it
  216.         printf("Value %d found at index %d.\n", value_to_find, index);
  217.     } else {
  218.         printf("Value %d was not found in the array.\n", value_to_find);
  219.     }
  220. }
  221.  
  222. /*
  223.  * This function displays all the numbers currently in the array
  224.  * Parameters:
  225.  *   arr[] - the array to display
  226.  *   current_size - how many numbers are in the array
  227.  */
  228. void print_array(const int arr[], int current_size) {
  229.     // Check if array is empty
  230.     if (current_size == 0) {
  231.         printf("The array is empty.\n");
  232.         return;
  233.     }
  234.  
  235.     // Print header showing how many elements we have
  236.     printf("Array contents (%d elements):\n[ ", current_size);
  237.  
  238.     // Print each number in the array
  239.     for (int i = 0; i < current_size; i++) {
  240.         printf("%d ", arr[i]);
  241.     }
  242.  
  243.     // Close the bracket to make it look nice
  244.     printf("]\n");
  245. }
  246.  
  247. /*
  248.  * This function finds which number in the array is closest to the average (mean)
  249.  * Parameters:
  250.  *   arr[] - the array to analyze
  251.  *   current_size - how many numbers are in the array
  252.  */
  253. void handle_find_closest_to_mean(const int arr[], int current_size) {
  254.     // Check if array is empty
  255.     if (current_size == 0) {
  256.         printf("The array is empty. Cannot calculate the mean.\n");
  257.         return;
  258.     }
  259.  
  260.     // Calculate the average of all numbers in the array
  261.     double mean = calculate_mean(arr, current_size);
  262.  
  263.     // Find which number is closest to this average
  264.     int closest_index = find_closest_to_value(arr, current_size, mean);
  265.  
  266.     // Show the results to the user
  267.     printf("The arithmetic mean of the array is: %.2f\n", mean);
  268.     printf("The element closest to the mean is %d at index %d.\n", arr[closest_index], closest_index);
  269. }
  270.  
  271. /*
  272.  * This function loads numbers from a text file into the array
  273.  * Parameters:
  274.  *   arr[] - the array to fill with numbers from the file
  275.  *   current_size - pointer to update with how many numbers were loaded
  276.  */
  277. void handle_load_from_file(int arr[], int* current_size) {
  278.     char filename[100]; // Array to store the filename (up to 99 characters + null terminator)
  279.  
  280.     printf("Enter the filename to load from: ");
  281.     scanf("%99s", filename); // Read filename, limit to 99 characters for safety
  282.     clear_input_buffer();
  283.  
  284.     // Try to open the file for reading
  285.     FILE* file = fopen(filename, "r"); // "r" means read mode
  286.     if (file == NULL) {
  287.         // If file couldn't be opened, print error message
  288.         perror("Error opening file");
  289.         return;
  290.     }
  291.  
  292.     int count = 0;
  293.     // Keep reading integers from the file until we reach MAX_SIZE or run out of numbers
  294.     while (count < MAX_SIZE && fscanf(file, "%d", &arr[count]) == 1) {
  295.         count++; // Successfully read a number, so increment counter
  296.     }
  297.  
  298.     // Close the file when we're done
  299.     fclose(file);
  300.  
  301.     // Update the array size with how many numbers we actually loaded
  302.     *current_size = count;
  303.     printf("Successfully loaded %d integers from '%s'.\n", *current_size, filename);
  304. }
  305.  
  306. /*
  307.  * This function saves all numbers from the array to a text file
  308.  * Parameters:
  309.  *   arr[] - the array containing numbers to save
  310.  *   current_size - how many numbers are in the array
  311.  */
  312. void handle_save_to_file(const int arr[], int current_size) {
  313.     // Check if there's anything to save
  314.     if (current_size == 0) {
  315.         printf("The array is empty. Nothing to save.\n");
  316.         return;
  317.     }
  318.  
  319.     char filename[100]; // Array to store the filename
  320.  
  321.     printf("Enter the filename to save to: ");
  322.     scanf("%99s", filename); // Read filename safely
  323.     clear_input_buffer();
  324.  
  325.     // Try to open the file for writing
  326.     FILE* file = fopen(filename, "w"); // "w" means write mode (creates new file or overwrites existing)
  327.     if (file == NULL) {
  328.         // If file couldn't be opened, print error message
  329.         perror("Error opening file for writing");
  330.         return;
  331.     }
  332.  
  333.     // Write each number to the file, one per line
  334.     for (int i = 0; i < current_size; i++) {
  335.         fprintf(file, "%d\n", arr[i]); // Write number followed by newline
  336.     }
  337.  
  338.     // Close the file when we're done
  339.     fclose(file);
  340.  
  341.     printf("Successfully saved %d integers to '%s'.\n", current_size, filename);
  342. }
  343.  
  344. /*
  345.  * This function searches for a specific value in the array
  346.  * Parameters:
  347.  *   arr[] - the array to search in
  348.  *   size - how many elements are in the array
  349.  *   value_to_find - the number we're looking for
  350.  * Returns: the index where the value was found, or -1 if not found
  351.  */
  352. int search_array(const int arr[], int size, int value_to_find) {
  353.     // Check each element in the array
  354.     for (int i = 0; i < size; i++) {
  355.         if (arr[i] == value_to_find) {
  356.             return i; // Found it! Return the index
  357.         }
  358.     }
  359.     return -1; // Didn't find it, return -1 to indicate "not found"
  360. }
  361.  
  362. /*
  363.  * This function calculates the average (arithmetic mean) of all numbers in the array
  364.  * Parameters:
  365.  *   arr[] - the array of numbers
  366.  *   size - how many numbers are in the array
  367.  * Returns: the average as a decimal number
  368.  */
  369. double calculate_mean(const int arr[], int size) {
  370.     // If array is empty, return 0
  371.     if (size == 0) {
  372.         return 0.0;
  373.     }
  374.  
  375.     // Use long long to avoid overflow when adding large numbers
  376.     long long sum = 0;
  377.  
  378.     // Add up all the numbers
  379.     for (int i = 0; i < size; i++) {
  380.         sum += arr[i];
  381.     }
  382.  
  383.     // Calculate and return the average
  384.     // Cast to double to get decimal result instead of integer division
  385.     return (double)sum / size;
  386. }
  387.  
  388. /*
  389.  * This function finds which element in the array is closest to a target value
  390.  * Parameters:
  391.  *   arr[] - the array to search in
  392.  *   size - how many elements are in the array
  393.  *   target_value - the value we want to find the closest match to
  394.  * Returns: the index of the element that's closest to the target value
  395.  */
  396. int find_closest_to_value(const int arr[], int size, double target_value) {
  397.     // Start by assuming the first element is closest
  398.     int closest_index = 0;
  399.  
  400.     // Calculate how far the first element is from the target
  401.     // fabs() gives us the absolute value (always positive distance)
  402.     double min_difference = fabs((double)arr[0] - target_value);
  403.  
  404.     // Check all other elements to see if any are closer
  405.     for (int i = 1; i < size; i++) {
  406.         // Calculate distance from current element to target
  407.         double current_difference = fabs((double)arr[i] - target_value);
  408.  
  409.         // If this element is closer than our current best, remember it
  410.         if (current_difference < min_difference) {
  411.             min_difference = current_difference;
  412.             closest_index = i;
  413.         }
  414.     }
  415.  
  416.     return closest_index; // Return the index of the closest element
  417. }
Advertisement
Add Comment
Please, Sign In to add comment