do-while loop

I am not quite understanding how to change this program into a do-while loop. Can anyone help me please?

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;
}
Please use code tags in future! Here is how a do...while loop differs from a while loop.
1
2
3
4
5
int x = 0; 
while(x < 10)
{
    ++x; 
}

And now a do while loop:
1
2
3
4
5
int x = 0; 
do
{
     ++x; 
}while(x < 10); 


So to change a while loop into a do...while loop, you just place do where while once was and then add the while condition after the closing brace, followed by a semi-colon.
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>

using namespace std;

int main()
{
   int number, product = 1, count = 0;
   
   do 
   {
      cout << "Enter a whole number to be included in the product" << endl;
      cout << "or enter 0 to end the input: ";
      cin >> number;
      
      if (number != 0)
      {
         product = product * number;
         count++;
         
         cout << "Enter a whole number to be included in the product" << endl;
         cout << "or enter 0 to end the input: ";
         cin >> number;
      } // End if statement.    
      
      else if (number == 0)
      {
         return 0;
      } // End else if statement.
   } // End do statement.
   
   while (count > 0);
   
   cout << endl << "The product is " << product << "." << endl;
   
   return 0;
} // end function main 


Like this? It still does't work
After you enter a zero, the else if statement will work.
However, the command you use is return 0. So the program will end and the cout command at the end will never be executed.

You may move the cout statement into the else if statement before returning 0 and the product will be printed out before the program end.
Topic archived. No new replies allowed.