1.For Loop
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | #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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | #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
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!