首页 > 后端开发 > C++ > 正文

C程序计算等差数列的第N项

WBOY
发布: 2023-09-01 14:09:07
转载
1486人浏览过

c程序计算等差数列的第n项

Given ‘a’ the First term, ‘d’ the common difference and ‘n’ for the number of terms in a series. The task is to find the nth term of the series.

So, before discussing how to write a program for the problem first we should know what is Arithmetic Progression.

Arithmetic progression or arithmetic sequence is a sequence of number where the difference between the two consecutive terms is same.

Like we have first term i.e a =5, difference 1 and nth term we want to find should be 3. So, the series would be: 5, 6, 7 so the output must be 7.

So, we can say that Arithmetic Progression for nth term will be like −

百度智能云·曦灵
百度智能云·曦灵

百度旗下的AI数字人平台

百度智能云·曦灵 83
查看详情 百度智能云·曦灵
AP1 = a1
AP2 = a1 + (2-1) * d
AP3 = a1 + (3-1) * d
..<p>APn = a1 + (n-1) *</p>
登录后复制

So the formula will be AP = a + (n-1) * d.

Example

Input: a=2, d=1, n=5
Output: 6
Explanation: The series will be:
2, 3, 4, 5, 6 nth term will be 6
Input: a=7, d=2, n=3
Output: 11
登录后复制

Approach we will be using to solve the given problem

  • Take first term A, common difference D, and N the number of series.
  • Then calculate nth term by (A + (N - 1) * D)
  • Return the Output obtained from the above calculation.

Algorithm

Start
   Step 1 -> In function int nth_ap(int a, int d, int n)
      Return (a + (n - 1) * d)
   Step 2 -> int main()
      Declare and initialize the inputs a=2, d=1, n=5
      Print The result obtained from calling the function nth_ap(a,d,n)
Stop
登录后复制

Example

#include <stdio.h>
int nth_ap(int a, int d, int n) {
   // using formula to find the
   // Nth term t(n) = a(1) + (n-1)*d
   return (a + (n - 1) * d);
}
//main function
int main() {
   // starting number
   int a = 2;
   // Common difference
   int d = 1;
   // N th term to be find
   int n = 5;
   printf("The %dth term of AP :%d</p><p>", n, nth_ap(a,d,n));
   return 0;
}
登录后复制

输出

The 5th term of the series is: 6
登录后复制

以上就是C程序计算等差数列的第N项的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号