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. |
|
|
Type in an even amount of numbers: 1 2 3 4 5 6 7 8 9 10 Figuring numbers: Sum of 1 and 2 is 3 Sum of 2 and 3 is 5 Sum of 3 and 4 is 7 Sum of 4 and 5 is 9 Sum of 5 and 6 is 11 Sum of 6 and 7 is 13 Sum of 7 and 8 is 15 Sum of 8 and 9 is 17 Sum of 9 and 10 is 19 Sum of 10 and 0 is 10 Sum of 1 and 2 is 3 Sum of 3 and 4 is 7 Sum of 5 and 6 is 11 Sum of 7 and 8 is 15 Sum of 9 and 10 is 19 Sum of index 1 and 10 is 11 Sum of index 2 and 9 is 11 Sum of index 3 and 8 is 11 Sum of index 4 and 7 is 11 Sum of index 5 and 6 is 11 |
#include <vector> #include <iostream> int main() { std::vector<int> storage; int input; std::cout << "Type in an even amount of numbers: " << std::endl; while(std::cin >> input) { storage.push_back(input); } std::cout << "Figuring numbers: " << std::endl; int vecSize = storage.size() - 1; // loop through vector and give sum of 1st and 2nd, then 2nd // and 3rd, 3rd and 4th, and so on for(int j = 0; j <= vecSize; ++j) { // poorly done as the last iteration of this loop adds 10 + 0 // I should have checked to see if j+1 was null and if it was // break out of the loop std::cout << "Sum of " << storage[j] << " and " << storage[j+1] << " is " << storage[j] + storage[j+1] << std::endl; } // loop through vector and give sum of adjacent values 1 and 2, // 3 and 4, 5 and 6, etc. for(int k = 0; k < vecSize;) { std::cout << "Sum of " << storage[k] << " and " << storage[k + 1] << " is " << storage[k] + storage[k + 1] << std::endl; k+=2; } // loop through the vector and give sum of first and last, // second and second to last, and so on for (int i = 0; i <= (vecSize/2); i++) { std::cout << "Sum of index " << storage[i]<< " and " << storage[vecSize -i] << " is " << storage[i] + storage[vecSize - i] << std::endl; } return 0; } |
|
|
Type in an even amount of numbers: 1 2 3 4 5 6 7 8 9 10 -999 Figuring numbers: Sum of 1 and 2 is 3 Sum of 2 and 3 is 5 Sum of 3 and 4 is 7 Sum of 4 and 5 is 9 Sum of 5 and 6 is 11 Sum of 6 and 7 is 13 Sum of 7 and 8 is 15 Sum of 8 and 9 is 17 Sum of 9 and 10 is 19 Sum of 10 and 0 is 10 Sum of 1 and 2 is 3 Sum of 3 and 4 is 7 Sum of 5 and 6 is 11 Sum of 7 and 8 is 15 Sum of 9 and 10 is 19 Sum of index 1 and 10 is 11 Sum of index 2 and 9 is 11 Sum of index 3 and 8 is 11 Sum of index 4 and 7 is 11 Sum of index 5 and 6 is 11 |
|
|
|
|
|
|