I need help please!!

Below is the code for displaying distance between time=0 till time=4 with interval of 0.5

I have several questions:
1) why do the /t=t+interval/ can not be placed before the /while/
2) if i put the /t=t+interval/ right befor the printf, it will display the distance untill time is 4.5 and not 4... why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 #include <stdio.h>
int main(void) {
double max_time, interval,  distance, a,t;
    max_time=4;
    interval=0.5;
    t=0;
    a=9.8;


while(t<=max_time)
{


    printf("distance is %lf     time is %lf \n", distance, t);
     t=t+interval;distance=0.5*a*t*t;
}



return 0
;}
Last edited on
1) why do the /t=t+interval/ can not be placed before the /while/
if it was before the while it would be executed only once, but it needs to be executed on each pass through the loop.

2) if i put the /t=t+interval/ right befor the printf, it will display the distance untill time is 4.5 and not 4... why?
Think of the sequence of events.
• When is the printf() executed, and what will be the current value of t.
• when is the while loop condition tested, and what will be the current value of t.
Thankyou I understand now.

I have another question..

Why CAN the //distance=0.5*a*t*t;// be placed AFTER the //printf// ???
If I think of the sequence, if it is placed after the printf, then the computer will get instruction to printf the distance without first knowing the formula for distance?
The first time through the loop, you're going to print garbage for distance.
Line 3, you declare distance, but do not initialize it.
Line 14, you attempt to print distance, but the value is garbage.

So yes, the calculation needs to be before the printf.
Last edited on
whoa the garbage it displays is 0 which is coincidence with the initial distance if calculate with the right formula

do you have an ebook recomendation for learning C ?
Topic archived. No new replies allowed.