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 |
除教程外,本网站大部分文章来自互联网,如果有内容冒犯到你,请联系我们删除!