C程序中的前n个自然数之和
n = 4
Now we will find the sum of numbers for every number from 1 to 4 :
Sum of numbers till 1 = 1 Sum of numbers till 2 = 1 + 2 = 3 Sum of numbers till 3 = 1 + 2 + 3 = 6 Sum of numbers till 4 = 1 + 2 + 3 + 4 = 10 Now we will find the sum of sum of numbers til n : Sum = 1+3+6+10 = 20登录后复制
方法1 - 使用for循环(低效)
方法2 - 使用数学公式(高效)
方法1 - 使用for循环
在这种方法中,我们将使用两个for循环来找到和的和。内部循环找到自然数的和,外部循环将此和添加到sum2并将数字增加一。
示例
#include int main() { int n = 4; int sum=0, s=0; for(int i = 1; i< n; i++){ for(int j= 1; j