C/C++ Adding Vectors in C++: Example Code for Summing Elements with an Offset Amount

Click For Summary
To solve the problem of adding corresponding elements from two vectors, a for-loop is necessary. The task involves iterating through each index of the `origList` and `offsetAmount`, summing the values at each index, and printing the results. The example provided illustrates that for `origList` containing {40, 50, 60, 70} and `offsetAmount` containing {5, 7, 3, 0}, the output should be the sums: 45, 57, 63, and 70. The discussion emphasizes the need for a clear implementation of the for-loop to achieve this output.
ineedhelpnow
Messages
649
Reaction score
0
im going through previous assignments to study for a test and i can't seem to remember how i did this one.

Add each element in origList with the corresponding value in offsetAmount. Print each sum followed by a space. Ex: If origList = {40, 50, 60, 70} and offsetAmount = {5, 7, 3, 0}, print:

45 57 63 70
Sample program:

Code:
#include <iostream>
#include <vector>
using namespace std;

int main() {
   const int NUM_VALS = 4;             
   vector<int> origList(NUM_VALS); 
   vector<int> offsetAmount(NUM_VALS); 
   int i = 0;                         

   origList.at(0) = 40;
   origList.at(1) = 50;
   origList.at(2) = 60;
   origList.at(3) = 70;

   offsetAmount.at(0) = 5;
   offsetAmount.at(1) = 7;
   offsetAmount.at(2) = 3;
   offsetAmount.at(3) = 0;

   <STUDENT CODE>
   cout << endl;

   return 0;
}

(Wondering)
 
Technology news on Phys.org
ineedhelpnow said:
im going through previous assignments to study for a test and i can't seem to remember how i did this one.

Add each element in origList with the corresponding value in offsetAmount. Print each sum followed by a space. Ex: If origList = {40, 50, 60, 70} and offsetAmount = {5, 7, 3, 0}, print:

45 57 63 70

Hi! (Smile)

It sounds like a for-loop in which you add elements.
What kind of for-loop can you can up with? (Wondering)
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 15 ·
Replies
15
Views
4K
  • · Replies 5 ·
Replies
5
Views
8K
  • · Replies 3 ·
Replies
3
Views
7K
Replies
2
Views
5K
  • · Replies 22 ·
Replies
22
Views
3K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 25 ·
Replies
25
Views
2K
  • · Replies 10 ·
Replies
10
Views
2K
  • · Replies 23 ·
Replies
23
Views
3K
Replies
12
Views
3K