Advertisement
janac

Sum of a list of numbers

Nov 4th, 2021 (edited)
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.56 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. // This function returns the sum of a list of numbers.
  6. int sum(vector<int> list)
  7. {
  8.     int total = 0; // Start with a total of zero.
  9.    
  10.     // Go from the beginning to the end of the list.
  11.     for (size_t i = 0; i < list.size(); ++i)
  12.     {
  13.         // Add each number to the sum.
  14.         total += list[i];
  15.     }
  16.  
  17.     return total;
  18. }
  19.  
  20. int main()
  21. {
  22.     // Create a list of numbers.
  23.     vector<int> number_list = { 1, 2, 3, 4, 5, 6 };
  24.    
  25.     // Display the sum of the numbers.
  26.     cout << sum(number_list) << endl;
  27.  
  28.     return 0;
  29. }
  30.  
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement