Question
Sum of First N Natural Numbers using while loop in C Language
Solution
✔ Verified
This C program calculates the sum of the first N natural numbers using a while loop.
The user is prompted to enter a positive integer N, and the program uses a while loop to iterate from 1 to N, adding each number to a cumulative total. This demonstrates the use of looping and basic arithmetic operations in C.
#include <stdio.h>
int main() {
int n, i = 1, sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
while(i <= n) {
sum += i;
i++;
}
printf("Sum = %d\n", sum);
return 0;
}
Output:-
Enter a number: 15
Sum = 120Click here to download practice questions on
While loop in C