Since the formula for calculating the sum of the terms of an arithmetic progression is as follows::
Being:
Sn = Sum of terms;
a1 = First term;
q = Reason;
n = number of terms;
This coded formula for the C language will be:
((a1*(pow(q,n) - 1))/(q-1))
However, there is an error in your code, in this excerpt:
for (i=0; i<=n-1; i++){
printf("%lf\n", a1);
a1=a1*q;
}
You are assigning values to the first term, if the purpose of the code were only to present the terms would be correct, however in this way your sum of the terms will be incorrect, to correct such error use an auxiliary variable to show the terms, I used the variable termo
, but you can rename it.
termo=a1;
for (i=0; i<=n-1; i++){
printf("O termo da posição %d = %.0f\n", i, termo);
termo=termo*q;
}
Your code with some adjustments will look like this:
#include <stdio.h>
#include <math.h>
int main(){
double a1, sn, termo;
int i, q, n;
printf("Insira o 1º Terno: ");
scanf ( "%lf", &a1);
printf("Insira a razão : ");
scanf ( "%d", &q);
printf("Insira a quantidade de termos: ");
scanf ( "%d", &n);
termo=a1;
for (i=0; i<=n-1; i++){
printf("O termo da posição %d = %.0f\n", i, termo);
termo=termo*q;
}
sn = ((a1*(pow(q,n) - 1))/(q-1));
printf("Soma dos termos da PG é: %.0f", sn);
return 0;
}
Note: I didn’t understand why you are using double for the terms, however I didn’t modify anything related to this, only the output %.0f
to display the numbers without the decimal part.
If there is any question regarding formatting I advise the readings:
Format specification syntax: printf and wprintf functions
C Tutorial - printf, Format Specifiers, Format Conversions and Formatted Output
Welcome, the calculation of the sum of the terms of pg is: Sn = (a1 (q n - 1)/(q-1) correct? then already this:
Sn = ((a1*(pow(q,n) - 1))/(q-1))
;– Luiz Augusto