c++ loop | Sololearn: Learn to code for FREE!

+3

c++ loop

You are on a 5 hour sea voyage. The ship sails at a speed of 40 km per hour. Write a program that will output how many kilometers the ship has traveled by each hour. My attempt is in the comments

c++

9/19/2021 3:50:59 PM

Mando

11 Answers

New Answer

+4

1. You're missing a closing brace on your for loop 2. You should take the speed and multiply it by the number of hours to get the distance rather than calculate the distance first.... for(int hours = 1; hours <= 5; hours++) { cout << hours * 40 << endl; }

+2

It count up. hour++ is hours = hours + 1 We need to increment in the loop

+2

It get incremented by one on each iteration – just like the k in your attempt

+1

Lisa but wouldnt that make hours = 2?

0

#include <iostream> using namespace std; int main() { int distance = 0; for (int k = 40; k < 200; k+=40){ cout << "k" << endl; return 0; }

0

I don't understand what you intend with the for loop. Can you explain, please? According to the task description, you should only do one calculation and output.

0

Lisa It should output 40 80 120 160 200

0

Ah, okay, sorry! Misunderstood the question!

0

Martin Taylor what is the hours++ for?

0

Mando, yes the hours will be incremented to 2. The first time through the loop hours = 1 so the output is 1 * 40 = 40. The increment occurs at the end of the loop not at the point where the for statement appears; that's simply the syntax used. The compiler knows what to do.

0