- 1C Hello World Program
- 2C Program to Print Your Own Name
- 3C Program to Print an Integer Entered by the User
- 4C Program to Add Two Numbers
- 5C Program to Multiply Two Floating‑Point Numbers
- 6C Program to Print the ASCII Value of a Character
- 7C Program to Swap Two Numbers
- 8C Program to Calculate Fahrenheit to Celsius
- 9C Program to Find the Size of int, float, double and char
- 10C Program - Add Two Complex Numbers
- 11C Program - Find Simple Interest
- 12C Program - Find Compound Interest
- 13C Program - Area And Perimeter Of Rectangle
- 14C Program - Check Whether a Number is Positive, Negative, or Zero
- 15C Program - Check Whether Number is Even or Odd
- 16C Program - Check Whether a Character is Vowel or Consonant
- 17C Program - Find Largest Number Among Three Numbers
- 18C Program - Calculate Sum of Natural Numbers
- 19C Program - Print Alphabets From A to Z Using Loop
- 20C Program - Make a Simple Calculator
- 21C Program - Generate Multiplication Table
- 22C Program - Reverse a Number
- 23C Program - Check whether the input number is a Neon Number
- 24C Program - Find All Factors of a Natural Number
C Program – Calculate Sum of Natural Numbers - Loop & Formula
Sum of Natural Numbers Using Loop
#include <stdio.h>
int main() {
int N, i;
int sum = 0;
printf("Enter a positive integer: ");
scanf("%d", &N);
for (i = 1; i <= N; i++) {
sum += i;
}
printf("Sum = %d\n", sum);
return 0;
}
Enter a positive integer: 5
Sum = 15
This method iterates from 1 up to the user-specified limit and adds each number to an accumulator variable. The result is printed after the loop completes.
Sum of Natural Numbers Using Formula
#include <stdio.h>
int main() {
int N;
int sum;
printf("Enter a positive integer: ");
scanf("%d", &N);
sum = N * (N + 1) / 2;
printf("Sum = %d\n", sum);
return 0;
}
Enter a positive integer: 10
Sum = 55
The formula N × (N + 1) / 2 provides a constant-time way to compute the sum of the first N natural numbers without iteration. This is especially useful for large values of N.
⬅ Previous TopicC Program - Find Largest Number Among Three Numbers
Next Topic ⮕C Program - Print Alphabets From A to Z Using Loop
Next Topic ⮕C Program - Print Alphabets From A to Z Using Loop
Comments
Loading comments...