How do I calculate x^y (x to the power of y)???

Hello,
this is a quick one:
This is part of the code of something I'm working on:

for (intIndex = 1; intIndex <= max_intIndex; intIndex++) {
Serial.print("intIndex: "); Serial.println(intIndex);
number += intArray[intIndex]*10TO_THE_POWER_OFpowerIndex;
powerIndex--;
}

Now.. How do I do that? How do I calculate intArray[intIndex] TO THE POWER OF max_intIndex???

Thanks!

Note: I had to take the CODE tags of to highlight that.. Sorry.

If x and y are floats, or you don't mind the overhead, you can use the pow function.

If x and y and integers, then x^y is just x times itself y times. A for loop to multiply x by itself y times will work.

There may be a better way to do whatever it is you are trying to do. Can you explain what is in the array, and where it came from, and what you are trying to construct from the array?

It looks like you are trying to take an array of integers, like 1, 2, 6, and 3, and construct a number like one thousand, two hundred sixty three from it. Is that right?

keep in mind that x^y might not (probably not, in some cases) fit into the datatype of x or y.

It looks like you are trying to take an array of integers, like 1, 2, 6, and 3, and construct a number like one thousand, two hundred sixty three from it. Is that right?

That's correct.
Here's the code:

    for (intIndex = 1; intIndex <= max_intIndex; intIndex++) {
      floatNumber += intArray[intIndex]*(pow(10,powerIndex));
      delay(5);
      powerIndex--;
    }

It works fine. But I don't like the fact that it is a float. How could I calculate the POWER without using floats without using the For loop? (the loop seems too hard for such a simple thing)

To multiply repeatedly, you have to loop somewhere.
There's a common algorithm for converting (1,2,3,4) to (1234) where the loop through the digits is used to collect the multiplications as well:

number=0;
for (intIndex = 1; intIndex <= max_intIndex; intIndex++) {
   number = number*10 + intArray[intIndex];
}

@westfw

That works GREAT! Thank you!

Go here to see the full code (and the original thread). :slight_smile: