Looping a chunk of code

I need to loop from "please enter the molar concentration" to the end. The program should end when the user enters 0 for the concentration. What is the correct way to loop this?

[code]
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double molar_concentration, pH;


{
cout << "CMPSC 201 - Homework 3" << endl;
cout << "Classify solutions as acidic or nonacidic" << endl << endl;
cout << "Please enter a molar concentration <or enter 0 to exit>: ";
cin >> molar_concentration;
cout << endl << "Molar Concentration = " << scientific << molar_concentration << endl;
pH = -log10(molar_concentration);
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(6);
cout << "pH = " << pH << endl;
if (pH > 14)
{
cout << "Molar concentration is invalid, pH can not be above 14" << endl;
}
else if (pH < 0)
{
cout << "Molar concentration is invalid, pH can not be below 0" << endl;
}
else if (pH <= 14 && pH > 7)
{
cout << "Nonacidic" << endl;
}
else if (pH == 7)
{
cout << "Neutral" << endl;
}
else if (pH >= 0 && pH < 7)
{
cout << "Acidic" << endl;
}
}

return 0;
}
The trick is to do it in an "infinite" loop, and break out in the middle of the loop:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
#include<cmath>
using namespace std;
int 
main()
{
    double molar_concentration, pH;

    cout << "CMPSC 201 - Homework 3" << endl;
    cout << "Classify solutions as acidic or nonacidic" << endl << endl;
    while (true) {
	cout << "Please enter a molar concentration <or enter 0 to exit>: ";
	cin >> molar_concentration;
	if (molar_concentration == 0 || !cin)
	    break;
	cout << endl << "Molar Concentration = " << scientific << molar_concentration << endl;
	pH = -log10(molar_concentration);
	cout.setf(ios :: fixed);
	cout.setf(ios :: showpoint);
	cout.precision(6);
	cout << "pH = " << pH << endl;
	if (pH > 14) {
	    cout << "Molar concentration is invalid, pH can not be above 14" << endl;
	} else if (pH < 0) {
	    cout << "Molar concentration is invalid, pH can not be below 0" << endl;
	} else if (pH <= 14 && pH > 7) {
	    cout << "Nonacidic" << endl;
	} else if (pH == 7) {
	    cout << "Neutral" << endl;
	} else if (pH >= 0 && pH < 7) {
	    cout << "Acidic" << endl;
	}
    }

    return 0;
}

Topic archived. No new replies allowed.