Вопрос задан 01.11.2023 в 15:19. Предмет Информатика. Спрашивает Турбина Аня.

Помогите с написание программы CИ (C комментариями пожалуйста ) Дан массив целых чисел

размерности n (n вводится с клавиатуры). случае, если элементы, стоящие на нечетных индексах образуютвозрастающую последовательность, получить среднее арифметическое четных элементов, иначе – количество положительных элементов.
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Бридько Алексей.

Ответ:

#include<iostream>

#include<ctime>

#include<iomanip>

using namespace std;

void FillArray(int*& arr, int size)

{

for (int i = 0; i < size; i++)

{

 arr[i] = rand() % 100;

}

}

void ShowArray(int*& arr, int size)

{

for (int i = 0; i < size; i++)

{

 cout << arr[i] << "  ";

}

cout << endl << endl;

}

bool CheckArray(int*& arr, int size, int& sum, int& k, int& ki)

{

bool incSeq = 1;

for (int i = 0; i < size; i++)

{

 if (arr[i] % 2 == 0)

 {

  sum += arr[i];

  ki++;

 }

 if (arr[i] > 0)

 {

  k++;

 }

}

for (int i = 1; i < size; i += 2)

{

 if (arr[i] > arr[i + 2])

 {

  incSeq = 0;

  break;

 }

}

return incSeq;

}

int main()

{

srand(time(0));

setlocale(LC_ALL, "ru");

int sum = 0;

int k = 0;

int ki = 0;

int size = 0;

cout << "Укажите размер массива - ";

cin >> size;

int* arr = new int[size];

FillArray(arr, size);

ShowArray(arr, size);

CheckArray(arr, size, sum, k, ki);

if (CheckArray)

{

 cout << "\n\nСредне арифметическое равно  " << fixed << setw(6) << setprecision(2) << (double)(sum / ki);

}

else

{

 cout << "\n\nКол-во чет. эл-ов\n\n - " << k;

}

delete[]arr;

}

Объяснение:

0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

Для решения данной задачи на языке C, вам потребуется использовать циклы, условные операторы и массивы. Вот пример программы, которая решает данную задачу:

```c #include

int main() { int n; printf("Введите размерность массива: "); scanf("%d", &n);

int arr[n]; printf("Введите элементы массива: "); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); }

int sum = 0; int count = 0; int increasing = 1; // флаг, указывающий на возрастающую последовательность

for (int i = 1; i < n; i += 2) { if (arr[i] <= arr[i - 1]) { increasing = 0; break; } }

if (increasing) { for (int i = 0; i < n; i += 2) { if (arr[i] % 2 == 0) { sum += arr[i]; } } printf("Среднее арифметическое четных элементов: %.2f\n", (float)sum / (n / 2)); } else { for (int i = 0; i < n; i++) { if (arr[i] > 0) { count++; } } printf("Количество положительных элементов: %d\n", count); }

return 0; } ```

В этой программе мы сначала запрашиваем размерность массива `n` с помощью функции `scanf`. Затем мы создаем массив `arr` размерности `n` и заполняем его элементами, которые также вводятся с помощью функции `scanf`.

Далее мы проверяем, образуют ли элементы, стоящие на нечетных индексах, возрастающую последовательность. Для этого мы используем цикл `for`, который проходит по нечетным индексам массива и сравнивает текущий элемент с предыдущим. Если найдется хотя бы одна пара элементов, где следующий элемент меньше или равен предыдущему, то флаг `increasing` устанавливается в 0, что означает, что последовательность не является возрастающей.

Если флаг `increasing` равен 1, то элементы на нечетных ин#### Writing a C program to calculate the average of even elements or count positive elements based on the sequence of odd-indexed elements

Sure! I can help you with that. Here's a C program that calculates the average of even elements if the elements at odd indices form an increasing sequence. Otherwise, it counts the number of positive elements.

```c #include

int main() { int n; printf("Enter the size of the array: "); scanf("%d", &n);

int arr[n]; printf("Enter the elements of the array:\n"); for (int i = 0; i < n; i++) { scanf("%d", &arr[i]); }

int sum = 0; int count = 0; int increasing = 1; // flag to check if odd-indexed elements form an increasing sequence

for (int i = 1; i < n; i += 2) { if (arr[i] <= arr[i - 2]) { increasing = 0; break; } }

if (increasing) { for (int i = 0; i < n; i += 2) { if (arr[i] % 2 == 0) { sum += arr[i]; count++; } } double average = (double) sum / count; printf("The average of even elements is: %.2lf\n", average); } else { for (int i = 0; i < n; i++) { if (arr[i] > 0) { count++; } } printf("The number of positive elements is: %d\n", count); }

return 0; } ```

Let's go through the program step by step:

1. We start by including the necessary header file `stdio.h` for input/output operations.

2. In the `main()` function, we declare a variable `n` to store the size of the array. We prompt the user to enter the size of the array and read the input using `scanf()`.

3. We declare an array `arr` of size `n` to store the elements of the array. We prompt the user to enter the elements of the array using a `for` loop and read the input using `scanf()`.

4. We initialize variables `sum` and `count` to keep track of the sum of even elements and the count of positive elements, respectively. We also initialize a flag variable `increasing` to `1` to assume that the odd-indexed elements form an increasing sequence.

5. We use a `for` loop to iterate through the odd-indexed elements (starting from index 1) and check if they are in increasing order. If any element is less than or equal to the previous element, we set the `increasing` flag to `0` and break out of the loop.

6. If the `increasing` flag is still `1`, it means that the odd-indexed elements form an increasing sequence. We use another `for` loop to iterate through the even-indexed elements (starting from index 0). If an element is even, we add it to the `sum` and increment the `count`.

7. We calculate the average of even elements by dividing the `sum` by the `count` and store it in a variable `average`. We then print the average with two decimal places using `printf()`.

8. If the `increasing` flag is `0`, it means that the odd-indexed elements do not form an increasing sequence. We use another `for` loop to iterate through all the elements of the array and count the positive elements.

9. Finally, we print the count of positive elements using `printf()`.

That's it! You can compile and run this program to test it with different inputs. Let me know if you have any further questions!

0 0

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос