# arduino programming

I an facing a weird problem while programming with arduino >:(
I am trying to find the sum of an array using the following program :
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}

void loop() {
// put your main code here, to run repeatedly:
int b[10];
b[0]=2;
b[1]=4;
b[2]=5;
b[3]=4;
int num=0;

for(int j=3,k=0;j>=0;j--,k++){
num=num+(b[j]*pow(10,k));
}
Serial.println(num);
delay(500);
}

But when I run it on arduino it automatically substracts 2 when number is 4 digit and 1 when it is 3 digit. I am storing the the digits in the array and then finding it by using the power method.

Why not make your code a bit longer and hence easier to debug rather than trying to cram everything into two lines. I doubt if it will make any difference to the size or performance of the finished code after the compiler has had its fun with it.

...R

pow() produces a floating point number that could be like 99.9999, which would be truncated to 99 when you go back to integers (instead of 100, like you expect.)

The usual algorithm for converting a set of digits to a number goes from left to right, successively multiplying by 10:

``````for (i=0; i < NUMDIGITS; i++) {
num = num*10 + b[i];
}
``````

(note that after 4 digits, your first digit will have been multiplied by ten three times, which is what you want.)
(and this is probably hundreds to thousands of times more efficient than using pow())

pow(10,k) results in a floating point number and the algorithm used does not give exact powers of 10 but slightly less and since you are converting the result to an int and not rounding the error is exaggerated .

The easiest way to evaluate a polynomial (which is what you have is) is to use

num = num * 10 + b[j];

I'm too slow.