-3

I have an array contain 100 elements. Can anyone help me to figure out how to write loops that perform this:

data[0] = 1/(2*3*4)
data[1] = 1/(4*5*6)
data[2] = 1/(6*7*8)
...
data[99] = 1/(200*201*202)


data[0]-data[1]+data[2]-data[3]+data[4]-data[5]+...+data[98]-data[99]

I just can't understand how to start. Any suggestions would be appreciated!

  • 1
    Look at functions... then try something like data[i]=operation(j) where operation is a function that does return 1 / ( (j)*(j+1)*(j+2) ), then increment j and i. – The Marlboro Man Dec 04 '13 at 09:27

3 Answers3

1

Try this

double c=0;
for (int i=0;i<100;i++)
{
 c=i*2+2;
 data[i]=1/(c*(c+1)*(c+2));
}
for (int i = 0; i < 100; i+=2)
{
  op+= data[i] - data[i+1];
}
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
Linga
  • 10,379
  • 10
  • 52
  • 104
0

My suggestions how to start, if you really want them and want to manage this by your own:

  1. Generalize your algorithm:
    1. Find a function f(x) such that data[i] = f(i)
    2. Just write the algorithm in your native language.
  2. Then learn basic operators of C language, including loop construct.
  3. Write your "native language algorithm" in C language.
klm123
  • 12,105
  • 14
  • 57
  • 95
0

Just in one loop:

int total = 0;
for(size_t i=0; i<100; ++i){
  int temp = (i+1)*2;
  data[i] = 1/(temp*(temp+1)*(temp+2));
  total = total + (i%2==0?data[i]:-data[i]);
}
Constantin
  • 8,721
  • 13
  • 75
  • 126
  • Nice one! But you need parenthesis around your ternery `?` expression due to operator precedence. Right now it will be interpreted as: `total = (total + i%2==0)?data[i]:-data[i]`. So add parenthesis like this: `total = total + (i%2==0?data[i]:-data[i]);` – Klas Lindbäck Dec 04 '13 at 10:08
  • @KlasLindbäck That's right - thank you. I edited it accordingly. – Constantin Dec 04 '13 at 10:20