I'm very new and taking an online cpp class. My teacher has a lab due before teaching any of the loop info, so i've been trying to figure it out myself.
My assignment is to make a program that loops products until 0 is entered, and then it displays the product.
So far I have:
#include <iostream>
using namespace std;
int main()
{
int user_input;
int product=1;
cout<<"/\\/\\ The Multiplier /\\/\\"<<endl;
do
{
cout<<"Enter a number to be multiplied"<<endl;
cin>>user_input;
product=product * user_input;
} while (user_input !=0);
cout<<"Product: "<<product;
}
I know that if I output the product before the while statement it comes out correctly, what I don't understand is why it gets reset to 0 after the while statement.
It becomes 0 because your process is out of order. First you ask the user for a number, then you process the calculation, then you verify whether it's 0 or not. So, no matter what the user entered previously, product*0 = 0, thus, the loop will exit and print 0.
What you are doing is displaying what the product is AFTER the while loop in nullified. To fix this, but the cout<< "Product: "<< product;in the dowhile loop. I also suggest initializing product at the beginning of the loop:
1 2 3 4 5 6 7 8 9 10 11
//...
do
{
product = 1;
cout<<"\nEnter a number to be multiplied"<<endl;
cin>>user_input;
product=product * user_input;
cout<<"Product: "<<product;
}
while (user_input !=0);