累加求和是循环的经典案例,用什么实现呢?
当然是循环啦
循环有while语句、do-while语句、for语句,三种语句我们都来试试吧
1.while语句实现
#includeint main(){int i=1,n,sum=0;printf("n:");scanf("%d",&n);while(i<=n){sum+=i;i++;}printf("sum=%d",sum);return 0;}
2.for语句实现
#includeint main(){int i=1,n,sum=0;printf("n:");scanf("%d",&n);for(;i<=n;i++){sum+=i;}printf("sum=%d",sum);return 0;}
自己用do-while语句试一试