### Nested Loop Help

So, I've written part of this program, basically just gathering all the info so far. But, I need the program to now calculate, and calculate on an interval. How do I do this with a nested loop? Am I on the right track with the for loop?

Thanks very much for any input.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354`` `````` #include #include #include using namespace std; // Define constants. #define a 3.952 #define b 0.0427 #define R 0.08206 #define mL_L .001 int main () { float moles; //IN: Number of moles of CO2 (n). float temp; //IN: Temperature (K). float initial; //IN: Initial volume (mL). float final; //IN: Final volume (mL). float increment; //IN: Increment volume (mL) b/w lines of the table. float pressure; //OUT: Pressure (atm). float loopVol; //Variable assignment for loop function. float volume; //Variable assignment for calculations. //Request user input. cout << "\nEnter the quantity of Carbon Dioxide (moles): "; cin >> moles; cout << "\nEnter the Temperature (K): "; cin >> temp; cout << "\nEnter the Initial Volume (mL): "; cin >> initial; cout << "\nEnter the Final Volume (mL): "; cin >> final; cout << "\nEnter the Volume Increment (mL): "; cin >> increment; //Set for table. cout << "\n\nVolume (mL) Pressure (atm)" << endl; //Begin calculations. for(loopVol = initial; loopVol <= final; loopVol += increment) { printf(" %.2f", loopVol); volume = loopVol * mL_L; pressure = (moles * R * temp)/(volume - b * moles) - (a * moles * moles)/(volume * volume); printf(" %.4f",pressure); } while (loopVol <= final); return 0; }``````
The "while" part of your code doesn't do anything by the way. Your code will be interpreted like this:
 ``1234567891011`` ``````for(loopVol = initial; loopVol <= final; loopVol += increment) { printf(" %.2f", loopVol); volume = loopVol * mL_L; pressure = (moles * R * temp)/(volume - b * moles) - (a * moles * moles)/(volume * volume); printf(" %.4f",pressure); } while (loopVol <= final) ;``````

In other words the code contains a "for" loop and then a "while" loop. By the time the "while" loop executes, loopVol will be greater than "final" because if it wasn't, then the "for" loop would still be executing.

A "for" loop is really just shorthand for a "while" loop. Any "for" loop like this:
 ``123`` ``````for (a; b; c) { code; }``````

is equivalent to this:
 ``1234567`` ``````{ a; while (b) { code; c; } }``````

Hope this helps. If you're still having trouble then explain what you're trying to compute.
Wow, thanks. That helped a lot! Now, I'm just having trouble having the results print in a tabular form. They're printing in a strange space array. But, I'm not sure how to do either of the following which I think would fix the issue:

(a) use setw in conjunction with printf
(b) change to cout to use setw, but still retrieve previous answers

Am I over-complicating the process?
Topic archived. No new replies allowed.