程序查找前n
个自然数的总和。我们将看到计算自然数的总和的两个 C 程序。在第一个 C 程序中,我们使用for
循环查找总和,在第二个程序中,我们使用while
循环执行相同操作。
要了解这些程序,您应该熟悉以下C 编程概念:
示例 1:使用for
循环查找自然数之和的程序
用户输入n
的值,程序使用for
循环计算前n
个自然数的总和。
#include <stdio.h>
int main()
{
int n, count, sum = 0;
printf("Enter the value of n(positive integer): ");
scanf("%d",&n);
for(count=1; count <= n; count++)
{
sum = sum + count;
}
printf("Sum of first %d natural numbers is: %d",n, sum);
return 0;
}
输出:
Enter the value of n(positive integer): 6
Sum of first 6 natural numbers is: 21
示例 2:使用while
循环查找自然数的总和
#include <stdio.h>
int main()
{
int n, count, sum = 0;
printf("Enter the value of n(positive integer): ");
scanf("%d",&n);
/* When you use while loop, you have to initialize the
* loop counter variable before the loop and increment
* or decrement it inside the body of loop like we did
* for the variable "count"
*/
count=1;
while(count <= n){
sum = sum + count;
count++;
}
printf("Sum of first %d natural numbers is: %d",n, sum);
return 0;
}
输出:
Enter the value of n(positive integer): 7
Sum of first 7 natural numbers is: 28
看看这些相关的 C 程序: