累加——从1至n
程序核心——循环语句
程序
#include<stdio.h>
int main()
{
int i,n,sum;
printf("Enter n:");
scanf("%d",&n);
sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf("Sum of number for 1 to %d is %d
",n,sum);
return 0;
}
结果
Enter n:100
Sum of number for 1 to 100 is 5050
--------------------------------
Process exited after 2.731 seconds with return value 0
请按任意键继续. . .
分析
重点:循环语句for的运行次数控制易错