Answer the question
In order to leave comments, you need to log in
Enter N integers into a 1-dimensional array. Calculate the number of array elements=0 and the sum of their indices. How to implement a dynamic array?
That is, the user enters N numbers into the array. That is, you cannot create an array of 10 places and run the loop. Suddenly, the user will type 2 characters, that is, it will be necessary to somehow finish ... How to be here?
It will not be difficult to calculate the number of 0s
and the sum of their indices... But to create a Dynamic array.
How would you do?
In general, apart from
int main()
{
cout << "Enter array size";
int size;
cin >> size;
int *arr = new int[size];
}
Answer the question
In order to leave comments, you need to log in
I have not programmed in C and C++ for 18 years, so there may be errors)
#include <iostream>
#include <cstdlib>
void main(void){
// переменная для общего колличество значений
int n;
// переменная для колличества значений==0
int zero = 0;
// переменная для суммы индексов со значениями==0
int zeroindex = 0;
// ввод пользователем колличества значений
std::cout << "введите колличество значений:";
std::cin >> n;
// Выделение памяти, достаточной для массива из n int
int* arr = (int*)std::malloc(n*sizeof(int));
// ввод пользователем n значений
for (int i = 0; i < n; i++ ){
std::cout << "введите значение №" << i << ":";
std::cin >> arr[i];
// если введен 0 то увеличиваем счетчик zero
if( arr[i] == 0){
zero++;
zeroindex+=i;
}
}
// выводим результаты расчетов
std::cout << "колличество значений равных нулю:" << zero;
std::cout << "сумма их индексов:" << zeroindex;
// освобождаем выделеную память перед выходом
std::free(arr);
}
usually use collections (or vectors or lists ), which behave exactly like dynamic arrays. all mechanics are hidden "under the hood". just take the appropriate one from among the ready-made templates, and use
the plus specifics you will have to study on your own. in sharpe would be most suitableList<int>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question