How can i convert this while statement to do while?

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int number, product = 1, count = 0;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
while (number != 0) 
{
product = product * number;
count++;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
}
if (count > 0)
{
cout << endl << "The product is " << product << "." << endl;
}


Add more information about what you want your code to do...
It does sound like a homework, where one construct has to be transformed into another construct. The challenge is thus to cope with the fact that "while" may evaluate its body 0 times, but "do while" has to do something at least once.
There's always the easy way, which involves copying the while loop into a do/while loop but only performing the operations inside it when applicable. Of course, the answer is highly dependent on what you're trying to do. But this ensures that the operations inside your do/while loop are not performed when they shouldn't be.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int number, product = 1, count = 0;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
do
{
if (number!=0)
   {
product = product * number;
count++;
cout << "Enter a whole number to be included in the product"
<< endl << "or enter 0 to end the input: ";
cin >> number;
   }
}while (number != 0); 
if (count > 0)
{
cout << endl << "The product is " << product << "." << endl;
}
Last edited on
Topic archived. No new replies allowed.