Loop Exercises
C program to find sum of natural numbers from 1 to n
Write a C program to find the sum of all natural numbers between 1 to n using for loop. How to find sum of natural numbers in a given range in C programming. Logic to find sum of all natural numbers in a given range in C programming.
Example
Input
Input upper limit: 10
Output
Sum of natural numbers 1-10: 55
Required knowledge
Basic C programming, Relational operators, For loop
Logic to find sum of natural numbers from 1 to n
Step by step descriptive logic to find sum of n natural numbers.
1.Input upper limit to find sum of natural numbers. Store it in some variable say N.
2.Initialize another variable to store sum of numbers say sum = 0.
3.In order to find sum we need to iterate through all natural numbers between 1 to n. Initialize a loop from 1 to N, increment loop counter by 1 for each iteration. The loop structure should look like for(i=1; i<=N; i++).
4.Inside the loop add previous value of sum with i. Which is sum = sum + i.
5.Finally after loop print the value of sum.
Program to find sum of natural numbers from 1 to n
/** * C program to find sum of natural numbers between 1 to n */ #include <stdio.h> int main() { int i, n, sum=0; /* Input upper limit from user */ printf("Enter upper limit: "); scanf("%d", &n); /* Find sum of all numbers */ for(i=1; i<=n; i++) { sum += i; } printf("Sum of first %d natural numbers = %d", n, sum); return 0; }
Note: In above program I have used shorthand assignment operator sum += i which is equivalent to sum = sum + i.
Output
Enter upper limit: 10
Sum of first 10 natural numbers = 55
Program to find sum of natural numbers in given range
/** * C program to find sum of natural numbers in given range */ #include <stdio.h> int main() { int i, start, end, sum=0; /* Input lower and upper limit from user */ printf("Enter lower limit: "); scanf("%d", &start); printf("Enter upper limit: "); scanf("%d", &end); /* Find sum of all numbers */ for(i=start; i<=end; i++) { sum += i; } printf("Sum of natural numbers from %d to %d = %d", start, end, sum); return 0; }
Output
Enter lower limit: 10
Enter upper limit: 15
Sum of natural numbers from 10 to 15 = 75