查詢算術級數和的 C 語言程式
問題
求算術級數和,使用者需要輸入首項、項數和公差。
解決方案
算術級數(A.P.)是一系列數字,其中任意兩個連續數字之差總是相同。這裡,項數標為 Tn。
Sum of A.P. Series: Sn = n/2(2a + (n – 1) d) Tn term of A.P. Series: Tn = a + (n – 1) d
演算法
請參考以下演算法以查詢算術級數。
Step 1: Declare variables.
Step 2: Initialize sum=0
Step 3: Enter first number of series at runtime.
Step 4: Enter total number of series at runtime.
Step 5: Enter the common difference at runtime.
Step 6: Compute sum by using the formula given below.
sum = (num * (2 * a + (num - 1) * diff)) / 2
Step 7: Compute tn by using the formula given below.
tn = a + (num - 1) * diff
Step 8: For loop
i = a; i <= tn; i = i + diff
i. if(i != tn)
printf("%d + ", i);
ii. Else,
printf("%d = %d", i, sum);
Step 9: Print new line程式
以下是查詢算術級數和的 C 語言程式−
#include <stdio.h>
int main() {
int a, num, diff, tn, i;
int sum = 0;
printf(" enter 1st no of series: ");
scanf("%d", &a);
printf(" enter total no's in series: ");
scanf("%d", &num);
printf("enter Common Difference: ");
scanf("%d", &diff);
sum = (num * (2 * a + (num - 1) * diff)) / 2;
tn = a + (num - 1) * diff;
printf("
sum of A.P series is : ");
for(i = a; i <= tn; i = i + diff){
if(i != tn)
printf("%d + ", i);
else
printf("%d = %d", i, sum);
}
printf("
");
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP