Print first and last element of a vector
Feb 2, 2022 at 3:40am UTC
Read a set of integers into a vector. Print the sum of each
pair of adjacent elements. Change your program so that it prints the sum of
the first and last elements, followed by the sum of the second and second-to last, and so on.
When running this programming, the output for adding the first and last element is equal to 11 for every output of the while loop. Why is 11 the output for every incrementation of the while loop and how might this code be improved?
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main()
{
vector<int > v1;
int num;
int incr = 0;
while (cin >> num) {
v1.push_back(num);
}
if (v1.size() == 0)
{
cout << "The vector is empty" ;
}
else if (v1.size() == 1)
{
cout << "The vector has no adjacent elements" ;
}
else
{
cout << '\n' << endl;
for (incr; incr != v1.size() - 1; incr++)
{
cout << v1[incr] + v1[incr + 1] << endl;
}
}
incr = 0;
cout << '\n' << "value of incr: " << incr << '\n' << endl;
int sizer = v1.size() / 2;
int sized = v1.size();
while (incr != sizer)
{
cout << v1[incr] + v1[sized - 1 - incr] << endl;
cout << "the value of incr is: " << incr << endl;
incr++;
}
return 0;
}
Feb 2, 2022 at 7:53am UTC
Perhaps your input vector contains the values 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Feb 2, 2022 at 10:48am UTC
Possibly using iterators:
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
#include <iostream>
#include <vector>
#include <iterator>
int main() {
std::vector<int > v1;
for (int num; std::cin >> num; v1.push_back(num));
if (v1.empty())
std::cout << "The vector is empty\n" ;
else if (v1.size() == 1)
std::cout << "The vector has no adjacent elements\n" ;
else {
std::cout << '\n' ;
for (auto itr {std::next(v1.begin())}; itr != v1.end(); ++itr)
std::cout << *itr + *std::prev(itr) << ' ' ;
std::cout << "\n\n" ;
for (auto itb {v1.begin()}, ite {std::prev(v1.end())}; itb < ite; ++itb, --ite)
std::cout << *itb + *ite << ' ' ;
std::cout << '\n' ;
}
}
Topic archived. No new replies allowed.