Making a square() function without x*x in C++

Viewed 9592

I am self-studying C++ and the book "Programming-Principles and Practices Using C++" by Bjarne Stroustrup. One of the "Try This" asks this:

Implement square() without using the multiplication operator; that is, do the x*x by repeated addition (start a variable result at 0 and add x to it x times). Then run some version of “the first program” using that square().

Basically, I need to make a square(int x) function that will return the square of it without using the multiplication operator. I so far have this:

int square(int x)
{
    int i = 0;
    for(int counter = 0; counter < x; ++counter)
    {
        i = i + x;
    }

return i;
}

But I was wondering if there was a better way to do this. The above function works, but I am highly sure it is not the best way to do it. Any help?

7 Answers
int square(int x) {
    int result = { 0 };
    int *ptr = &result;
    for (int i = 0; i < x; i++) {
        *ptr = *ptr + x;
    }
    return *ptr;
}

I am reading that book atm. Here is my solution.

 int square(int n) 
 { 
        // handle negative input 
        if (n<0) n = -n; 

         // Initialize result 
         int res = n; 

          // Add n to res n-1 times 
          for (int i=1; i<n; i++) 
          res += n; 

      return res; 
 } 
  //Josef.L
  //Without using multiplication operators.

int square (int a){
     int b = 0; int c =0;
    //I don't need to input value for a, because as a function it already did it for me.
    /*while(b != a){
            b ++;
        c = c + a;}*/
    for(int b = 0; b != a; b++){  //reduce the workload.
        c = c +a;
        //Interesting, for every time b is not equal to a, it will add one to its value:
        //In the same time, when it add one new c = old c + input value will repeat again.
        //Hence when be is equal to a, c which intially is 0 already add to a for a time.
        //Therefore, it is same thing as saying a * a.
    }
    return c;
}

int main(void){
    int a;
    cin >>a;
    cout <<"Square of: "<<a<< " is "<<square(a)<<endl;
return 0;
}

//intricate.

Related