Удалить первый элемент массива с заданным значением - C (СИ)

Узнай цену своей работы

Формулировка задачи:

Нужна помощь. Если можно с комментариями, буду очень благодарен. Задание: 1) Сформировать одномерный массив целых чисел, используя датчик случайных чисел. 2) Распечатать полученный массив. 3) Удалить первый элемент с заданным значением. 4) Сдвинуть массив циклически на К элементов вправо. 5) Распечатать полученный массив.

Решение задачи: «Удалить первый элемент массива с заданным значением»

textual
Листинг программы
  1. #include <stdio.h>
  2. #include <time.h>
  3. #include <Windows.h>
  4.  
  5. // Defined values for changing array size, low and high border of the array
  6. #define ARRAY_SIZE                  8
  7. #define NEW_ARRAY_SIZE  (ARRAY_SIZE-1)
  8. #define LOW_BORDER                -30
  9. #define HIGH_BORDER                30
  10.  
  11.  
  12. int main(void)
  13. {
  14.     srand(time(NULL));
  15.  
  16.     // Variables initialization
  17.     int i, j;
  18.     int arr[ARRAY_SIZE];
  19.     int new_arr[NEW_ARRAY_SIZE];
  20.     int del_el = 0, pos = 0, found = 0, shift = 0;
  21.    
  22.     for (i = 0; i < ARRAY_SIZE; i++)
  23.     {
  24.         // TASK1. Generating and printing in the console window generated array with rand() function
  25.         arr[i] = rand() % (HIGH_BORDER - LOW_BORDER + 1) + LOW_BORDER;
  26.         // TASK2. Outputting the generated array to the console
  27.         printf("%d  ",arr[i]);
  28.     }
  29.    
  30.     // Processing user's input of the element to be deleted
  31.     printf("\nEnter the element to be deleted: ");
  32.     scanf("%d", &del_el);
  33.    
  34.     // Search for the entered del_el element in array arr[ARRAY_SIZE]
  35.     for (i = 0; i < ARRAY_SIZE; i++)
  36.     {
  37.         if (arr[i] == del_el)
  38.         {
  39.             found = 1;
  40.             pos = i;
  41.             break;
  42.         }
  43.     }
  44.  
  45.     if (found == 1) // If element was found(entered correctly)
  46.     {
  47.         for (i = 0, j = 0; i < ARRAY_SIZE, j < NEW_ARRAY_SIZE; i++,j++)
  48.         {
  49.             if (i == pos)
  50.             {
  51.                 j--;
  52.                 continue;
  53.             }
  54.             new_arr[j] = arr[i];
  55.         }
  56.     }
  57.     else // Jump here if user has entered the element which is not in the array
  58.         printf("Element %d is not found in the vector\n", del_el);
  59.    
  60.     // TASK4. Shifting the array on the entered number of positions
  61.     printf("Enter the value of the right shift: ");
  62.     scanf("%d", &shift);
  63.  
  64.     shift %= NEW_ARRAY_SIZE;
  65.     while (shift)
  66.     {
  67.         int tmp = new_arr[NEW_ARRAY_SIZE - 1];
  68.         for (int i = NEW_ARRAY_SIZE - 1; i>0; i--)
  69.             new_arr[i] = new_arr[i - 1];
  70.             new_arr[0] = tmp;
  71.             shift--;
  72.     }
  73.  
  74.     // TASK5. Outputting the resultant array after all the operations
  75.     printf("The resultant array after the removing of the element with the entered value is \n");
  76.     for (i = 0; i < NEW_ARRAY_SIZE; i++)
  77.     {
  78.         printf("%d  ", new_arr[i]);
  79.     }
  80.     printf("\n");
  81.     system("pause");
  82.     return 0;
  83. }

Объяснение кода листинга программы

  1. Установить размер массива, границу нижнего и верхнего индексов
  2. Сгенерировать и вывести в консоль массив с помощью функции rand()
  3. Попросить пользователя ввести элемент для удаления
  4. Найти введенный элемент в массиве
  5. Создать новый массив с уменьшенным размером
  6. Сдвинуть элементы массива на введенное количество позиций вправо
  7. Вывести полученный массив в консоль

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

10   голосов , оценка 4.1 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы