-2

Okay so I am going through bjarn stroustrups book on c++ and one of his exercises asks me to calculate the square of a number without using the multiplication operator. so the boiler plate code that I started off with is a function called square of the type int with a parameter x of type int and the code block was return x*x; pretty simple. so I thought about it and I know I need a loop and I know it is probably a for loop. I know that I want the loop to sound something like this add x to x and loop this the value of x times. I am just starting out with c++ so I do not know how to create the loop. any ideas?

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1995779
  • 5
  • 1
  • 1
  • 1
    Read the manual? If you need to ask a question just for a `for`, you are going to do a lot questions. Read a manual, and if you have trouble with it come back. – SJuan76 Jan 21 '13 at 04:01
  • Man, it really sucks to try and edit a comment on a phone. I give up... too bad you can't delete a comment on mobile, either. – rodrigo-silveira Jan 21 '13 at 04:04
  • The chapter that asks you to do this should contain the information you need... – bames53 Jan 21 '13 at 04:09
  • Related question: [Perfect square or not?](https://stackoverflow.com/questions/12862637/perfect-square-or-not) – Cœur Oct 11 '18 at 09:00

2 Answers2

1

in your case b=2

 int pow(int a, int b)
    {
      if (b == 0)
        return 1;
      int answer = a;
      int increment = a;
      int i, j;
      for(i = 1; i < b; i++)
      {
         for(j = 1; j < a; j++)
         {
            answer += increment;
         }
         increment = answer;
      }
      return answer;
    }
Cris
  • 12,799
  • 5
  • 35
  • 50
1

So the whole point in this question is really just to make your own multiplication function. There's a few ways to do this. You could either do this recursively (personally I think this is easiest) or through loops. Recursively:

int mult(int a, int b){

    if (b == 0) {
        return 0;
    }

    b -= 1;

    return (a + mult(a, b));
}

int power(int base, int deg){
    if (deg == 0) {
        return 0;
    }

    deg-=1;

    return mult(base, base)+power(base, deg);
}

or as @Cris did above without recursion using nested for loops:

int pow(int a, int b)
    {
      if (b == 0)
        return 1;
      int answer = a;
      int increment = a;
      int i, j;
      for(i = 1; i < b; i++)
      {
         for(j = 1; j < a; j++)
         {
            answer += increment;
         }
         increment = answer;
      }
      return answer;
    }
Alex
  • 1,388
  • 1
  • 10
  • 19