quarter of a one-dimensional array

Pages: 12
It's not when you say what is required.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <vector>
#include <iostream>

int main()
{
	size_t noElems {};

	std::cout << "How many elements: ";
	std::cin >> noElems;

	std::vector<int> vi(noElems);

	std::cout << "Enter elements: ";
	for (auto& v : vi)
		std::cin >> v;

	const auto newsz {vi.begin() + vi.size() * 3 / 4};	// Just use 3/4 of vector

	size_t noOdd {};
	int sum {};

	for (auto it = vi.begin(); it != newsz; ++it)
		if (*it % 2) {
			++noOdd;
			sum += *it;
		}

	std::cout << "Average is: " << (sum + 0.0) / noOdd << '\n';
}

Topic archived. No new replies allowed.
Pages: 12