Loops in C++, Lesson 16, C++ Basics

Hey guys, I follow Ivan through the video and I feel I have a pretty good understanding of loops in general. Here is the code reprinted exactly from the video and I wanted to see if anyone could find the error. The code is supposed to print the total amount of miles of all three cars and yet it prints a new line after adding one at a time with the new total each time the loops iterates.

Here is what I have… (note: you can see I attempted Ivan’s tip on printing for every counter to track each iteration but that did not help my cause)

int main()
{
int numberOfCars = 3;
int carMiles [] = {15, 13, 15};

``````// total number of miles for all cars
//notice*** accessing carMiles[counter] = carMiles[0] aka first in the array
int totalMiles =  0;
for(int counter = 0; counter < numberOfCars; counter++){
cout<<"counter is now "<<counter<<endl;
totalMiles += carMiles[counter];
cout << "Total miles of all cars is "<<totalMiles<<endl;
}
``````

Thank you!

Where exactly does the new line print that you don’t want it? You could remove the `endl` command if you don’t want to print new lines.

You would want to pull the ‘cout’ to be after the loop is finished.
I hope this makes more sense… I just did pseudo code so you need to atleast apply it to the code.

for count = 0 to numberOfCars {
// … does your counting …
totalMiles += carMiles[counter] // Adds the previous value + new value
} // the end of the loop counter
// Print the total
count << "total: " << totalMiles << endl;

2 Likes

Ahh I see, I didn’t understood the question correctly.

1 Like

thank you!! this helps clarify for me what I was doing wrong

1 Like

Heh, thank you! I realize I could have been more clear.