Help with For Loops

I am in a beginners C++ programming class in college, and I can't seem to wrap my head around "for loops"
I have a program due by this Thursday the 29th of September.
The assignment basically requires that I write a program with a "for loop" that will output the height of an object each second after launch that has been launched with an inputted initial velocity. The formula is height= v*t - 1/2*g*t*t.
v = initial velocity
t = time (1,2,3,4...)
g = gravity (9.8)
If someone could help me identify an appropriate for loop that would be awesome.

I looked up a problem similar to this on the forums, it is the same problem but mine requires that I use a "for loop"

http://www.cplusplus.com/forum/general/39245/

If I need to clarify this better please let me know.
Last edited on
What exactly don't you understand about for loops? The loop required for this task is pretty much an one-liner.
See here for an explanation of for loops:
http://www.cplusplus.com/doc/tutorial/control/#for
for loops are simply while loops with an automated increasing or decreasing counter so you can iterate a calculation simply. you will want to do something like this:

1
2
3
4
5
6
7
8
9
10
//declare other variables
float i;
int time;
for(time = 1; time < whatever max time you want; time ++){
i = v*time-(g*time*time)/2;
printf("The height is %4.2f at time %d seconds", i, time); 


}
//any last operations 


the first parameter in the for part is saying the start value, then you say the ending value, then the last one means time will go up by one automatically every time the code reaches the end, until time < max time is no longer true, at which point the for loop ends and the program continues to code below it.
What if I need the time to be when the object hits the ground, or when it is going to a negative distance/0?
That would be basic math, not programming. Of course, you could just iterate ('for loop') over sufficient values of 't' until you see the result you desire.
I mean that the stopping point would have to be when the object hit the ground no matter what the velocity is.
If you have the formula for 'distance', just do this:

1
2
3
4
5
6
7
int time = 1;
float distance = (starting distance);

while (distance>0) {
  // Formulas for speed, acceleration and distance as needed
 ++time;
}
Last edited on
Topic archived. No new replies allowed.