### do x*x by repeated addition

I am attempting to implement square() without using the multiplication operator; that is, do x*x by repeated addition. For some reason, however, the number is only being added once, so I am getting x+x rather than x*x. Can anyone offer any suggestions as to what I am doing wrong? Many thanks.

 ``1234567891011121314`` ``````int number = 0; int result = 0; cout<<"What would you like to square? "; cin>>number; result = number; for (int counter = number; counter <= 0; counter--); { result += number; } cout<<"\nThe answer is: " <
The problem is with the loop condition.
`counter <= 0`
`for (int counter = number; counter <= 0; counter--)`
should be
`for (int counter = number; counter > 0; counter--)`
Also set result to 0, not number, or loop one less time.
`for (int counter = number; counter > 0; counter--);`

The semicolon at the end of this makes this repeat until counter is no longer > 0, then it executes the lines in brackets once and spits out the answer
Haha. Thank you! I can't believe I missed that!
No problem, took me a minute or two as well.
if you want to square a number use the
#include <cmath>

and use the pow(variable,2)
use this instead of the for loop
Topic archived. No new replies allowed.