Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C หาผลรวมของอนุกรมเลขคณิต (Arithmetic Progression)


โจทย์

หาผลรวมของอนุกรมเลขคณิต (A.P.) โดยรับ: จำนวนแรก (a), จำนวนพจน์ (n), ความต่างร่วม (d)

สูตร

ผลรวม S_n = n/2 * (2a + (n-1)d)
พจน์ที่ n: T_n = a + (n-1)d

อัลกอริทึม

  1. รับค่า a, n, d
  2. คำนวณ sum = n * (2*a + (n-1)*d) / 2
  3. คำนวณ tn = a + (n-1)*d
  4. แสดงอนุกรมและผลรวม

โปรแกรมตัวอย่าง

#include <stdio.h>
int main() {
    int a, n, d, tn, i, sum = 0;
    
    printf("Enter 1st number of series: ");
    scanf("%d", &a);
    printf("Enter total numbers in series: ");
    scanf("%d", &n);
    printf("Enter Common Difference: ");
    scanf("%d", &d);
    
    sum = (n * (2 * a + (n - 1) * d)) / 2;
    tn = a + (n - 1) * d;
    
    printf("\nSum of A.P. series: ");
    for(i = a; i <= tn; i += d) {
        if(i != tn) printf("%d + ", i);
        else printf("%d = %d", i, sum);
    }
    printf("\n");
    return 0;
}

ผลลัพธ์

enter 1st no of series: 3
enter total no's in series: 10
enter Common Difference: 5
sum of A.P series is: 3 + 8 + 13 + 18 + 23 + 28 + 33 + 38 + 43 + 48 = 255

enter 1st no of series: 2
enter total no's in series: 15
enter Common Difference: 10
sum of A.P series is: 2 + 12 + 22 + 32 + 42 + 52 + 62 + 72 + 82 + 92 + 102 + 112 + 122 + 132 + 142 = 1080