If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In C, to calculate the sum of the first N natural numbers (1+2+3+...+N), you can use a loop to iterate through the numbers and add them together.
Here is an example of how this can be done using a for loop:
Copy code
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter the value of n: ");
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += i;
}
printf("Sum of first %d natural numbers: %d", n, sum);
return 0;
}
This program prompts the user to enter an integer value for n, and then uses a for loop to iterate through the numbers from 1 to n, adding each number to the sum. Finally, it prints the result.
Alternatively, you can also use the formula to calculate the sum of natural numbers which is N*(N+1)/2,
Copy code
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter the value of n: ");
scanf("%d", &n);
sum = n*(n+1)/2;
printf("Sum of first %d natural numbers: %d", n, sum);
return 0;
}
This program also prompts the user to enter an integer value for n and then uses the formula to calculate the sum of the first n natural numbers. Finally, it prints the result.
It's important to note that the first program will have a time complexity of O(n) while the second program will have a time complexity of O(1) which is more efficient and faster.
Comments: 0