loops - multiplying numbers in vector out of order in C++ -


my name matt. i'm new stackoverflow , new c++. working way through c++ primer lippman.

i'm doing exercise in book, , task read integers in vector, , multiply integers doing first , last, second , second last, third , third last etc.

i did myself without looking up, or else i'd barely learn if copied... program compiles , acts expected. question is: did correctly? there more efficient way of doing it?

i not want learn how make working code, want correctly. thank in advance!

#include <iostream> #include <string> #include <vector> #include <cctype>  using std::cout; using std::cin; using std::vector; using std::endl; using std::string;   int main() {     vector<int> numbers;     int usernum = 0;      cout << "enter numbers: ";     while (cin >> usernum)     {         numbers.push_back(usernum);     }      unsigned maxelement = numbers.size() - 1;     unsigned minelement = 0;      (auto : numbers)     {         cout << numbers[minelement] << " * " << numbers[maxelement] << " = " << numbers[minelement] * numbers[maxelement] << "\n";         ++minelement;         --maxelement;     }      return 0; } 

in comment, said:

i've noticed doesn't work expected. goes through vector , multiplies twice maxelement goes right through beginning, , minelement goes through end. not sure how stop once it's done operation on each 1 time.

if don't want repeat multiplications, need change for loop bit.

for ( ; minelement <= maxelement; ++minelement, --maxelement) {     cout << numbers[minelement] << " * " << numbers[maxelement] << " = " << numbers[minelement] * numbers[maxelement] << "\n"; } 

ps

when use logic, you'll need make sure minelement , maxelement of signed type. otherwise, run problems if numbers has 1 element.


Comments

Popular posts from this blog

javascript - Thinglink image not visible until browser resize -

firebird - Error "invalid transaction handle (expecting explicit transaction start)" executing script from Delphi -

mongodb - How to keep track of users making Stripe Payments -