FAQ: Vectors - Operations

This community-built FAQ covers the “Operations” exercise from the lesson “Vectors”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Learn C++

FAQs on the exercise Operations

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

#include
#include

int main() {

std::vector delivery_order;

delivery_order.push_back(8.99);
delivery_order.push_back(3.75);
delivery_order.push_back(0.99);
delivery_order.push_back(5.99);

// Calculate the total using a for loop:

double total = 0.0;

for (int i = 0; i < delivery_order.size(); i++) {

delivery_order[i] == 3.75 + 0.99 + 5.99 + 8.99;

}

total == delivery_order[0];
std::cout << total << “\n”;

}

Why this program gives ‘0’ as the output? I wrote total == delivery_order[0]. In the for loop I declared delivery_order[i] == 3.75 + 0.99 + 5.99 + 8.99. So I feel that total == sum. Where am I wrong?

I understood the first point (i.e I should not use ‘==’ sign). But I did not understand the second point which says that I should have written total = delivery_order[i] and not total = delivery_order[0]. I think that both of these will give me the correct result as each element of the vector is equal to the same value.

First, after these lines of code execute:

std::vector <double> delivery_order;

delivery_order.push_back(8.99);
delivery_order.push_back(3.75);
delivery_order.push_back(0.99);
delivery_order.push_back(5.99);

you have a vector that looks like this: [8.99, 3.75, 0.99, 5.99] These elements of the vector can be accessed by their index (position) like so: delivery_order[0] The value of the element at index 0 is 8.99. The value at index 1 is 3.75, index 2 is 0.99 and index 3 is 5.99
Your for loop is supposed to be used to calculate the sum of those 4 values. The reason you are getting 0 as the output is this line: total == delivery_order[0] Since you used ==, you are testing a condtion. That line of code is testing whether the value of total which is still 0.0 is equal to the value of delivery_order[0] which is 8.99. That evaluates to false which is stored as 0 in C++.

To get the total as instructed, you need to access each element of the vector, one at a time, and add its value to the total variable. That is the purpose of the for loop.

Try to re-write your for loop’s code body, and get the correct result. I’ve included the solution below if you get stuck. Happy coding!

for (int i = 0; i < delivery_order.size(); i++) {
  total += delivery_order[i]; //this will add  each value in turn to the total
}

std::cout << total << "\n";
2 Likes

My second post after 14 days was meant for Mohamed Abdelkarem who answered my question. I received it in my email account. Somehow his post is not visible here. Do you have any idea why is it so?
I should not have used the ‘==’ sign in my program in the question. You wrote that " To get the total as instructed, you need to access each element of the vector, one at a time, and add its value to the total variable. That is the purpose of the for loop." What is the problem if I make each element of the vector equal to the sum of four numbers and equate the variable ‘total’ to any single element of the vector(all the elements are equal to sum of numbers in the vector)

I assume you’re referring to this line:

delivery_order[i] == 3.75 + 0.99 + 5.99 + 8.99;

What if you didn’t know what the 4 values were? What if you needed the 4 original values of the vector for a later operation? Your line of code above changes all of the values of the original vector to be the sum of the original values. Why would you need the same sum stored 4 times in a vector? Learning to access the values stored in an indexed collection of data without prior knowledge of those values, and without mutating them is an important concept in every programming language.

1 Like

I know that ‘total += delivery_order[i]’ essentially means ‘total = total + delivery_order[i]’. Can I use ‘total = total + delivery_order[i]’ in my function? (i.e is it correct syntax)
Thanks for all the answers.

You can, and it’s perfectly fine syntactically, it’s just shorter to use +=. Opting to use total = total + delivery_order[i] is really just a matter of personal preference. There’s nothing wrong with choosing readability and clarity over being concise.

1 Like

When using the for loop in vectors, how does the counter of it can be used as the index?

OK, I’ve been working at this for some time now and i can’t seem to get it to work. Every time i change something i get a new error then i start over and try again ever error has this: /usr/lib/gcc/x86_64-linux-gnu/7/…/…/…/x86_64-linux-gnu/crt1.o: In function _start': (.text+0x20): undefined reference tomain’
collect2: error: ld returned 1 exit status.

i dont know what that means to i dont know how to fix it and it tells me “Did you output the total ?”

this is the code i have so far:

#include
#include

int main() {

std::vector delivery_order;

delivery_order.push_back(8.99);
delivery_order.push_back(3.75);
delivery_order.push_back(0.99);
delivery_order.push_back(5.99);

// Calculate the total using a for loop:

double total = 0.0;

for (int i = 0; i < delivery_order.size(); i++) {

total += delivery_order[i];
}

std::cout << total << “\n”;
}

Your code looks fine. The error in the console is a problem with the website. I’ve seen other users report the same message, and I’ve seen it myself in the lesson on vectors. I submitted a bug report, and suggest you do the same. If you click on the Get Help icon in the lower right corner of the exercise page, you’ll see a section for reporting bugs. Hopefully this will get fixed soon. @sonnynomnom, any chance you can facilitate someone looking into this?

Thanks i did just that and the very next lesson i got the same error and did it again. i hope they get that fixed. thanks again.

1 Like

anyone know why instead of using delivery_order why does it use i?

1 Like

Hello, @i_have_a_dream.

Welcome to the forums.

Could you be a bit more specific, and possibly paste in an example of the code you are referring to?

Hello, 2 days into programming and I have the excercise all wrong:

#include <iostream>
#include <vector>
  
int main() {
  
  std::vector<double> delivery_order;
  
  delivery_order.push_back(8.99);
  delivery_order.push_back(3.75);
  delivery_order.push_back(0.99);
  delivery_order.push_back(5.99);
  
  // Calculate the total using a for loop:
  
  double total = 0.0;
  
  for (double delivery_order = 0; delivery_order < delivery_order.size(); delivery_order++ ){

total = total + delivery_order;
}

…and might be kinda stupid to ask but:

  1. why we use int variable? Both delivery_order vector and total variable are double. Aren’t int variables integer numbers , and double variables decimical numbers?

  2. as i_have_a_dream asked: why we use i instead of delivery_order ? We haven’t declared what i stands for in the code. (I am talking for the for loop: for ( int i = 0; …etc

I am so confused :confused:

Hello, @design3579020597.

Welcome to the forums.

delivery_order is a vector. A vector is an iterable data structure. It is made up of elements that can be accessed by their index. In your code, after these lines of code are executed:

  std::vector<double> delivery_order;
  
  delivery_order.push_back(8.99);
  delivery_order.push_back(3.75);
  delivery_order.push_back(0.99);
  delivery_order.push_back(5.99);

your delivery_order vector could be visualized like this: {8.99, 3.75, 0.99, 5.99}.
It has 4 elements. That means delivery_order.size() returns a value of 4.
The index values for the elements begin with 0. delivery_order[0] has a value of 8.99. delivery_order[3] has a value of 5.99 (the last element of the vector).

You want to use a for loop to get the total amount of the delivery_order elements added together.
It is common practice to use the variable name i for the variable used to access an indexed data collection element at a particular index.

for (int i = 0; i < delivery_order.size(); i++)

In the line above we initialize i as an int because it will only hold integer values. In this case those values will be used to access the elements of the delivery_order vector inside the code body of the for loop. We give i the initial value of 0 because the first element of our vector is at index 0.

The next part of the for loop is the stop condition. It tells the computer when to stop executing the code inside the body of the loop. In this case we want to stop when the value of i is no longer a valid index for our vector. The valid indexes are: 0, 1, 2, 3. We’ve already established that delivery_order.size() will return 4. When the value of i is equal to 4 it will no longer be less than 4, so control will pass to the next line of code outside the for loop code body.

The last part of the for loop declaration tells the computer how to increment the variable i. We’ve used i++;, so i will be incremented by 1 following each iteration of the loop.

Inside the for loop is where we perform the calculation to get the total of the elements inside the vector:

  for (int i = 0; i < delivery_order.size(); i++ ){

    total = total + delivery_order[i]; //the first time this is executed i is equal to 0, so 8.99 will be added to the total then i will be incremented to 1 and 3.75 will be added to the total, and so on...
    //this would work as well: total += delivery_total[i];
  }

Using this method, we successfully add the value of each element in the delivery_order vector to the value of total, and then exit the loop after we’ve added the last value.

1 Like

Thank you SO much midlindner for the answer. I willl go through it as you explained it line by line again. Thanks for the time you’ve put to write and explain it to me. I don’t think I can proceed to the next lessons/tasks if I don’t understand the logic exactly, so you’ve been really helpful. :slight_smile:

1 Like