# Thread: Just learning, problem with an excercise.

1. ## Just learning, problem with an excercise.

I have to do the following:
Read a number and calculate the following sequence:
1-1/2+1/3-1/4+1/5...1/n

This is the way I'm doing it, but it doesn't work:

Code:
```#include <stdio.h>

int main()
{
int a=0, n, suma=0;
float den;

printf ("\n Ingrese el número : ");
scanf ("%i", &n);

while (a<n)
{
if (a%2==0){
a++;
den=1/a;
suma-=den;}

else{
a++;
den=1/a;
suma+=den;}
}

printf ("\n Resultado secuencia = %i", suma);

return 0;
}```

2. I personally would (either in my head or on a sheet of paper) see what can be constructively noted about this function.

1. So it looks like the denominator simply gets incremented by one each time.
2. Even denominators get subtracted and odds added

So couldn't you make a very simple loop sheerly from this alone?

Example:
Code:
```\$denominator = 1
\$sum = 0.0;

while \$denominator < \$n+1
if iseven(\$denominator)
sum -= 1.0 / \$denominator
else
sum += 1.0 / \$denominator
loop```

3. Note also that:
When a==0 1/a is NaN
When a==1 1/a is 1
Every other a 1/a is 0

Maybe use 1.0/a instead.

4. Yeah but the variable a should surely be 1 to begin with. Oooooooooh ok, nevermind. I just saw that your post was totally directed toward the OP.

5. This is how it looks now:

Code:
```#include <stdio.h>

int main()
{
int a=0, n;
float den, suma=0.0;

printf ("\n Ingrese el n&#250;mero : ");
scanf ("&#37;i", &n);

while (a<n)
{
if (a%2==0){
a++;
den=1.0/a;
suma-=den;}

else{
a++;
den=1.0/a;
suma+=den;}
}

printf("%f", den);
printf ("\n Resultado secuencia = %f", suma);

return 0;
}```
But this is what I get:

Ingrese el n&#250;mero : 2
Resultado secuencia = -0.500000

Why the negative number?

6. Read my code (even if it is pseudo code) and read what tabstop suggested. I see a pattern...

Example:
Code:
```#include <stdio.h>

int main()
{
int a=1, n;
float suma=0.0f;

printf ("\n Ingrese el n&#250;mero : ");
scanf ("&#37;i", &n);

while (a<n)
{
if (a%2==0)
suma-=1.0f/a;
else
suma +=1.0f/a;}
a++;
}

// printf("%d", den); <- why? Who cares
printf ("\n Resultado secuencia = %d", suma);

return 0;
}```

7. Originally Posted by medeshago
This is how it looks now:

Code:
```#include <stdio.h>

int main()
{
int a=0, n;
float den, suma=0.0;

printf ("\n Ingrese el número : ");
scanf ("%i", &n);

while (a<n)
{
if (a%2==0){
a++;
den=1.0/a;
suma-=den;}

else{
a++;
den=1.0/a;
suma+=den;}
}

printf("%f", den);
printf ("\n Resultado secuencia = %f", suma);

return 0;
}```
But this is what I get:

Ingrese el número : 2
Resultado secuencia = -0.500000

Why the negative number?
Because you start by subtracting? You're currently doing -1 + 1/2 - 1/3 + 1/4 - ...

8. Thanks, now it works great.

9. You need to start placing your brackets a little more cleanly. But at least you did use [code] tags. So I will simply say: you're welcome.

Popular pages Recent additions