English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn to calculate the sum of natural numbers entered by the user.
To understand this example, you should know the followingC programming languageTopic:
Positive numbers1,2,3 ...Called natural numbers. Not exceeding10The sum of natural numbers is:
sum = 1 + 2 + 3 + ... + 10
#include <stdio.h> int main() { int n, i, sum = 0; printf("Enter a positive integer: "); scanf("%d", &n); for (i = 1; i <= n; ++i) { sum += i; } printf("Sum = %d", sum); return 0; }
The above program gets input from the user and stores it in the variable n. Then, it uses a for loop to calculate the sum of n.
#include <stdio.h> int main() { int n, i, sum = 0; printf("Enter a positive integer: "); scanf("%d", &n); i = 1; while (i <= n) { sum += i; ++i; } printf("Sum = %d", sum); return 0; }
Output the result
Enter a positive integer: 100 Sum = 5050
In both programs, the loop is iterated n times. In each iteration, the value of i is added to sum and i is incremented1.
Although both programs are technically correct, it is better to use a for loop in this case. Because the number of iterations is known.
If the user enters a negative integer, the above program cannot work properly. Here, a slight modification has been made to the above program. In this program, we keep getting input from the user until a positive integer is entered.
#include <stdio.h> int main() { int n, i, sum = 0; do { printf("Enter a positive integer: "); scanf("%d", &n); } while (n <= 0); for (i = 1; i <= n; ++i) { sum += i; } printf("Sum = %d", sum); return 0; }
Visit this page to learnHow to use recursion to find the sum of natural numbers.