Hints to compile as wanted

Im suppose to create a program in which i ask user for MPH and time traveled.
Hour Distance Traveled
1 80
2 160
3 240


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
      double vs; // vehicle speed 
      double hours; 
      double S_H;
    
      cout << " Enter the speed of the vehicle (MPH): " << endl;
      cin >> vs;

      cout << "Enter the period of time the vehicle has traveled (hours): " << endl;
      cin >> hours;

      S_H = hours * vs;
      
       int i; 
       for (i = vs; i < S_H; i++)
         {
               cout << "Hours   Distance Travalled" << endl;
              cout << i << " " <<endl;
         }




code is compiling incorrectly and i thinks its because of the i++ any help to compile accurately.
Last edited on
loop should be:
1
2
3
4
cout << "Hours   Distance Travalled" << endl;
for (i = 1; i <= hours; ++i) {
    cout << i << "\t" << i * vs << endl;
}
Last edited on
The problem isn't with i++ it's with your loop conditions. You're loop is going to run 120 times if the user inputs 40 and 3 because it's taking the product of these two as the for condition for how long the loop should run.

change i<S_H to i<hours and change i=vs to i=1. Then the loop should run the correct number of times. But that's not the only problem. Then the program would only display

1
2
3

With no additional values. So how do we get the others to show? Well the first one is easy. just add the following statement in your loop:

1
2
3
cout << "Hours   Distance Travalled" << endl;
              cout << i << " " <<vs<<endl;


so now we have
1 40
2 40
3 40

how do we update the value with each loop iteration? We use += on vs (MPH). But we need a temporary variable to hold the initial value so we don't lose it.

Example:

1
2
double temp;
temp = vs;


So, change your loop to look like the following:

1
2
3
4
5
6
 for (i = 1; i < hours; i++)
         {
               cout << "Hours   Distance Travalled" << endl;
               cout << i << " " << vs<<endl;
               vs += temp; //adds 40 (or whatever the user enters) with each iteration 
         }


You'll also realize after this that S_H is a variable that will not be needed in this program.
Last edited on
So you made the for loop for the time instead of the distance and just made the calculation after. Thank you, makes so much sense now.
thank you unsensible & MiiNiPaa. and thank you for the well detailed explanation i need that so i don't make this mistake again.
Topic archived. No new replies allowed.