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.
#include <iostream>
usingnamespace 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.
elseif (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
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.