How can I add the value of the result to the previous value?

1

I would like to know, how do I add the value of the sequence in the variable res and then print it? for example, enter the value of N equal to 2 and get the value 2.5 in the output?

#include <stdio.h>

int main (void)
{
    int N,i;
    float res;

    scanf("%d", &N);
    for( i = 1 ; i <= N; i++)
    {
        res = (float)i/((N - i) + 1);
    }
    printf("%.4f\n", res);
    return 0;
}
    
asked by anonymous 02.05.2015 / 02:24

1 answer

2

To do this, you can use the += / a> ( addition assignment ) to accumulate the result and initialize the res variable. The code should look like this:

#include <stdio.h>

int main (void){
    int N, i;
    float res = 0;
    puts("Digite um valor: ");
    scanf("%d", &N);

    for( i = 1; i <= N; i++){
        res += (float)i/((N - i) + 1);
    }
    printf("%.2f\n", res); // 2.50
    return 0;
}

DEMO

    
02.05.2015 / 02:34