Menu Close

C语言练习:使用for循环或while循环求前n个自然数的和

1.For Loop

#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): 100
Sum of first 100 natural numbers is: 5050

2.While Loop

#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): 100
Sum of first 100 natural numbers is: 5050
READ  C语言练习:检查整型,浮点数,双精度,字符型数据类型的字节
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Leave the field below empty!

Posted in C语言习题集

Related Posts