Advertisement
alaestor

vector and loops example

Oct 21st, 2019
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.62 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. int main()
  5. {
  6.     std::size_t num_of_elements;
  7.     std::cout << "Desired vector size: ";
  8.     std::cin >> num_of_elements;
  9.     std::vector<int> vec(num_of_elements);
  10.     std::cout << "Vector size is " << vec.size() << std::endl;
  11.     std::cout << "Value for each element:" << std::endl;
  12.     for (std::size_t i { 0 }; i < vec.size(); ++i)
  13.     { // using array [] indexing syntax
  14.         std::cout << "vec[" << i << "] = ";
  15.         std::cin >> vec[i];
  16.     }
  17.     int sum { 0 }; // calculated via ranged for
  18.     for (auto& element : vec) sum += element;
  19.     std::cout << "The sum the vector is " << sum << std::endl;
  20.     return 0;
  21. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement