Write a C program to find the sum of first N natural numbers.
int main () {
int n, sum = 0, i = 1;
/* get the input from user */
printf("Enter the value for n:");
scanf("%d", &n);
/* calculate the sum of first n natural numbers */
while (i <= n) {
sum = sum + i;
i++;
}
/* print the output */
printf("Sum of 1st %d natural numbers is %d\n", n, sum);
return 0;
}
Output:
jp@jp-VirtualBox:~/$ ./a.out
Enter the value for n:10
Sum of 1st 10 natural numbers is 55
Enter the value for n:10
Sum of 1st 10 natural numbers is 55
No comments:
Post a Comment