C Programming Problem (looping)
I've been working on this stupid program for hours.
When I execute I get this
Induced Current Table Creation
Input initial voltage: 1.10
Input ending voltage: 1.12
Input incremental voltage: 0.01
Input initial resistance: 1.001
Input ending resistance: 1.003
Input increment resistance: 0.001
Table Heading------------------------------------
1.100000 1.001000 1.098901
1.100000 1.002000 1.097804
1.100000 1.003000 1.096710
Table Heading------------------------------------
Table Heading------------------------------------
Input initial voltage:
What I can't figure out is why the other tables are being populated! Why is the inner most loop only being executed one time? I have a feeling it will be some trivial mistake that I can't see. Hopefully another pair of eyes will help me find the problem.
EDIT I think I found what is causing the problem. When I run the inner most loop once, the variable init_res value is never reset back to the original inputted value. So the statement "init_res <= end_res" is always false after I run it once. If that makes any sense. Now, how do I fix it?
teammatt3 posted this at 04:28 — 10th February 2007.
He has: 2,102 posts
Joined: Sep 2003
All I needed was a break (as in time away from the computer) . You can compare the two if you are interested.
The bad one : The good one
Basically, I added another var that held the original value of init_res, and after the inner most loop finished, it would reset init_res.
Abhishek Reddy posted this at 12:13 — 11th February 2007.
He has: 3,348 posts
Joined: Jul 2001
That's the right idea, however I would suggest a slightly more elegant version:
for(voltage = init_voltage; voltage <= end_voltage; voltage += increm_voltage)
{
puts("Table Heading"
"------------------------------------");
for(res = init_res; res <= end_res; res += increm_res)
{
printf(" %f %f %f \n", voltage, res, voltage / res);
}
}
The name [incode]init_res[/incode] is suggestive of a constant or parameter, something you don't want to destructively modify -- indeed, doing so caused your problem. It also doesn't represent the physics expression very well (init_voltage should mean initial voltage, not present voltage).
Assigning a variable ([incode]voltage[/incode] or [incode]res[/incode]) in the loop is handier since you don't have to manually reset anything, and it's just more readable.
Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.