### Need to place nested loop where nested isn't necessary

I wrote this code, and everything was working well, but part of the assignment is that it must include nested loops. Once I added the nested while loop, which is basically an if statement, my life was ruined. I am trying to nest a loop in the code that will basically tell the compiler that if the value "loopVol" were to exceed the value of "final" after adding an increment, to run the program for the "final". How can I do that?

Example:

initial = 10
final = 123
increment = 10

as of now, the program would stop at 120, but I want to nest a loop that will tell the compiler to calculate at the final if this happens.

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869`` ``````#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; //OUT: Variable assignment for loop function; ranges from initial to final by increment. 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. { loopVol = initial; do { while (loopVol <= final) { if ((loopVol += increment) >= final) { loopVol == final; continue; } } cout << setw(5) << setprecision(2) << fixed << loopVol; volume = loopVol * mL_L; pressure = (((moles * R * temp)/(volume - (b * moles))) - ((a * moles * moles)/(volume * volume))); cout << setw(38) << setprecision(4) << fixed << pressure << endl; loopVol += increment; } while (loopVol < final); } return 0; }``````
well at first glance why are you using double equals on line 52?
I just did that to see if the program would give me an output. When I have single equals, there's no output at all. I don't know what to do to make this darn thing work :(
Once you set loopVol = final - you get an infinite loop because the while is checking to see if loopVol <= final, which will then always be true. Did you mean to use a break statement instead of continue to stop the loop at that point?

 ``12345678910`` ``````do { while (loopVol <= final) { if ((loopVol += increment) >= final) { loopVol = final; //single equal sign continue; // break; ? } }``````
Last edited on
Topic archived. No new replies allowed.