### Help with squaring without multiplication

Hello everyone.

I am trying to create a program that will let me square numbers without multiplication but I always get negative answers. Any help?

 ``12345678910111213141516171819202122`` `````` #include "std_lib_facilities.h" using namespace std; int square (int x) //x is the base { for(int c=0;c<=x;++c) //How many times the base should be repeated { x+=x; //base being repeated } return x; } int main() { int v=0; cout<<"ready"<>v; // v is the input cout<
Instead of adding x times, you are doubling the value of x each time. In other orders, your program produces x*(2^x). If x is a large number, then probably you must be exceeding the int limit.

Change it to:

 ``12345678910`` ``````int square (int x) //x is the base { int initial_x = x; for(int c=0;c
Last edited on
There is a problem in both examples of trying to hit a moving target.

Original code:
 ``1234`` `````` for (int c=0; c<=x; ++c) { x+=x; }``````

Code from abhishekm71:
 ``1234`` `````` for (int c=0; c

Notice in both cases c is being compared with x or x-1. But x is changing each time around the loop, so the loop will not terminate as expected, that is not until x overflows and becomes negative.

You could do something like this:
 ``1234567891011`` ``````int square (int x) { int sq = 0; for (int c=0; c

Note that this won't give the correct result for negative values of x. You could fix that by inserting this at the start:
 ``12`` `````` if (x < 0) // allow for negative value x = -x; // x squared is always positive or zero. ``````
Last edited on
Thanks for the help, both of you.
Last edited on
Oops! Sorry, totally missed that.

Thanks for pointing out.
@abhishekm71 Don't worry. It happens to all of us.
Topic archived. No new replies allowed.