please help with simple code any feedback is good.

I am kinda off with this certain code and can not figure out what im doing wrong any feedback helps.

question : Design a While loop that lets the user enter a number. The number should be multiplied by 10, and the result stored in a variable named product. The loop should iterate as long as product contains a value less than 100.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
 #include <iostream>
#include <iomanip>  
#include <string>

using namespace std;


int main()

{
    int userinput;
    int product;
	    cout << "enter a number" << endl;
	    cin >> userinput;
	    while(userinput<=100){
	        product=userinput*10;
	         }
	    
	

	return 0;
}
The loop should iterate as long as product contains a value less than 100.




while(userinput <= 100){



You're looping on "userinput", not "product". In fact, you don't even need two variables, you could just make everything use "product", and remove the "userinput" variable.

Also, you should use consistent indentation. Right now it's all over the place.
https://en.wikipedia.org/wiki/Indentation_style#Styles
Last edited on
Hello starterpack6100,

Based on Ganado's suggestions I came up with this:
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
#include <iostream>
#include <iomanip>  
#include <string>

//using namespace std;  // <--- Best not to use.


int main()

{
	int userinput{}; // <--- Should be initialized to zero, but not necessary for this variable.
	int product{};   // <--- Should be initialized to zero.

	std::cout << "enter a number" << std::endl;
	std::cin >> userinput;

	while (product < 100)
	{
		product += userinput * 10;
		//product *= 10;
		std::cout << std::setw(3) << product << std::endl; // <--- Used for testing. May not be needed.
	}

        return 0;
}

What you can do to see the differences is on line 15 change "userinput", would work better as "userInput", note the (camelCase), to "product" to use one variable and switch the comments on lines 19 and 20.

Also on line 17 in the while condition change the "<" to "<=" and see the difference in the output.

Line 21 is optional. I put this in so you can see what is happening with the while loop.

It is always a good idea to initialize your variables. When I used line 20 it complained that the variable "product" was uninitialized and returned a compiler error until I fixed it. In your original code "product" is set to the result of the calculation, so it did not make any difference.

Line 20 changes the value of "product" each time through the loop. Your original code keep the same value of "product" each time through the loop making it an endless loop unless the value for "userInput" is large enough to exceed 100.

Hope that helps,

Andy
Topic archived. No new replies allowed.