do while loop?

thnk u
Last edited on
Your do-while loop is ok. The code inside has problems. What are you trying to do?
Im trying to change this "while" loop to a "do-while" loop.. @joe864864

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int number, product = 1, count = 0;
cout << "Enter an integer 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 an integer 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;
}

Last edited on
I believe this is what you needed to do (have not tested it). You moved everything in to the loop that wasn't their before. The only difference is that the while loop tests the condition before running the code so you could enter 0 the first time and exit the program. With the do-while loop it runs the code and then tests the condition, so if you entered 0 the first time it asks you you will still have to enter another number and wont exit an till 0 is entered in the loop. This code works but could use more work to optimize.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int number, product = 1, count = 0;
	cout << "Enter an integer number to be included in the product"
		<< endl << "or enter 0 to end the input: ";
	cin >> number;
	
	do
	{
		product = product * number;
		count++;
		cout << "Enter an integer 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;
	}
Here:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;

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

The product is 7.
Enter an integer number to be included in the product
 or enter 0 to end the input: 4

The product is 28.
Enter an integer number to be included in the product
 or enter 0 to end the input: 2

The product is 56.
Enter an integer number to be included in the product
 or enter 0 to end the input: 0

The product is 0.
Press any key to continue . . .
Topic archived. No new replies allowed.