For the last two hours, I’ve been stuck on this C++ programming practice question involving using the for loop. Help!?

Here’s what I did:

#include <iostream>

using namespace std;

int main ()


int distance = 0;

for (distance < 200; distance += 40;) {

cout << distance << endl;


return 0;



The answer sheet says the outputs should be 40, 80, 120; yet, my outputs are in fact 40, 80, 120. Clearly the program doesn’t like something that I’m doing to reach the same answer, my question is what the hell is it!?

Attachment image

3 Answers

  • Alan
    Lv 7
    4 weeks ago
    Favorite Answer

    You wrote your program based on knowing all outputs.

    Your program is supposed determine the

    correct output.  

    You're not supposed to do the math and 

    found a cryptic way to get the numbers. 

    Also, you can add word to your output. 

    This would be more straight forward and understandable. 

    int distance,hours; 

    distance = 0;  

    for (hours=1;hours<=5;hours++) 


    distance +=40;  

    cout<<"After "<<hours<<" hours, Distance Travelled: "<<distance <<endl; 


    Gives outputs 

    After 1 hours, Distance Travelled: 40

    After 2 hours, Distance Travelled: 80

    After 3 hours, Distance Travelled: 120

    After 4 hours, Distance Travelled: 160

    After 5 hours, Distance Travelled: 200

  • Anonymous
    4 weeks ago

    Don't work out the distance yourself that's for the computer to do!

    #include <iostream>

    int main() {

     int endTime = 5;

     int speed = 40;

     for(int time=1; time<=endTime; ++time) {

      int distance = speed * time;

      endl(std::cout << distance);



  • 4 weeks ago

    It's been a while since I've used C++, but I thought its syntax is the same as C's and java's.  You have:

    for (distance < 200; distance += 40;)

    But the syntax should be:

    for (initialize; if statement; update)

    So since you are pre-initializing the value outside of the for you'd want this to be:

    for (; distance < 200; distance += 40)


    Outside of that, I do see another problem.  Based on your logic here, the last number shown would be 160 which is the distance traveled after 4 hours.  You are asked to show the distance of each hour up to 5 hours.  So there's one small thing you have to change to correct this "off by one" error.

    In the fifth loop, what would the value of "distance" be and how would it react to the "if" condition of the for statement?  I'll leave the rest of the debugging to you.

Still have questions? Get your answers by asking now.