用迴圈(for\while\do...while)列印1到100的整數加和
阿新 • • 發佈:2019-02-14
//計算1、2、3、、、100這100個數的整數和
for語句
#include<stdio.h>
int main()
{
int a,sum;
sum = 0;
for (a = 1; a <= 100; a++)
{
sum = sum + a;
}
printf("整數和為%d\n",sum);
}
//while迴圈:
{
int a, sum;
sum = 0;
a = 1;
while (a <= 100){
sum +=a;
a++;
}
printf("整數和為%d\n" , sum);
}
//do...while語句
{
int a = 1, sum = 0;
{
do{
sum += a;
a++;
}
while (a <= 100);
printf("整數和為%d\n", sum);
}
}