# ¿Por qué aparece un error en la excepción Entrada fuera de rango?

``````int bNum=3;
int aNum=3;
for (int i = 0; i < bNum; i++)
{
for (int j = 0; j < aNum; j++)
{
b[i] += a[j];
b[i + 1] += a[j + 3];
b[i + 2] += a[j + 6];
}
}
``````

I basically want the following to happen:

``````b[0]=a[0]+a[1]+a[2];
b[1]=a[3]+a[4]+a[5];
b[2]=a[6]+a[7]+a[8];
``````

¿Qué pasa con mi lógica?

HAHA! OOPS! My sleepy eyes are accounting for the dumb question. I see that at every iteration it get computed multiple times.

preguntado el 31 de julio de 12 a las 10:07

What are the size of the arrays? That `i+3` is probably going above it. -

Estas usando `b[i + 6]` as an index. I assume you meant `b[2] = a[j + 6]` -

## 2 Respuestas

whatever language it is, you need to make constant index for b, variable index for a

`````` for (int j = 0; j < aNum; j++)
{
//here is loop-unrolling for b
b[0] += a[j];
b[1] += a[j + 3];
b[2] += a[j + 6];
}

for(k=0;k<max;k++)
{
for (int j = 0; j < aNum; j++)
{
//without loop-unrolling
b[k] += a[j+k*3];

}
}
``````

i made the "k" loop outer to let it read the a[] as continuously as possible. You can make "k" loop innerside but it makes reads of a[] jumping from here to there then coming back here again an jumping again, which makes it slow. this is not a vector though :P i just used it to fill the space

Respondido 16 ago 12, 11:08

Thank you! I was really tired and couldn't think straight. But I like your vectorized idea! - Ingeniero de al lado

The question is kind of contradictionary. The de largo of both arrays is equal, but the requirement stands to not have equal.

Asumiendo que el requeirement is correct, you can do the following

Para cada `b` elemento hay un suma de los siguiente 3 elements of the `a`

``````int bNum=3;
int aIndex = 0;
for (int i = 0; i < bNum; i++)
{
for (int j = 0; j < 3; j++)
b[i] += a[aIndex ++];

}
``````

There is no any array bounds control here. This is just a muestra code naturally.

Si esto no es lo que está buscando, por favor aclare.

Respondido 31 Jul 12, 11:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.