Write a C program to find sum of all prime numbers between 1 to n using for loop. C program to generate sum of all primes between a given range. Logic to find sum of prime numbers in a given range.
Example
Input
Input upper limit: 10
Output
Sum of prime numbers between 1-10: 17
Required knowledge
Basic C programming, If else, For loop, Nested loops
Must know – Program to find Prime numbers in a given range.
What is Prime number?
Prime numbers are positive integers greater than 1 that has only two divisors 1 and the number itself. For example: 2, 3, 5, 7, 11 are the first 5 prime numbers.
Logic to find sum of prime numbers between 1 to n
Step by step descriptive logic to find sum of prime numbers between 1 to n.
- Input upper limit to find sum of prime from user. Store it in some variable say end.
- Initialize another variable
sum = 0
to store sum of prime numbers. - Run a loop from 2 to end, incrementing 1 in each iteration. The loop structure should look like
for(i=2; i<=end; i++)
. - Inside the loop check if loop counter variable is prime or not. If i is prime then add i to sum i.e.
sum = sum + i
. - Finally after loop print the resultant value of sum.
Program to find sum of prime numbers between 1 to n
Program to find sum of prime numbers in given range
Output
Enter lower limit: 10 Enter upper limit: 20 Sum of all prime numbers between 10 to 20 = 60
Happy coding
Recommended post
- Loop programming exercises index.
- C program to find sum of natural numbers between 1 to n.
- C program to find the sum of even numbers between 1 to n.
- C program to find the sum of odd numbers between 1 to n.
- C program to find sum of elements of an array.
- C program to find factors of any number.
- C program to print perfect numbers in given range.