Loop Exercises
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.
Required knowledge
Basic C programming, If else, For loop, Nested loops
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
/** * C program to find sum of prime numbers between 1 to n */ #include <stdio.h> int main() { int i, j, end, isPrime, sum=0; /* Input upper limit from user */ printf("Find sum of all prime between 1 to : "); scanf("%d", &end); /* Find all prime numbers between 1 to end */ for(i=2; i<=end; i++) { /* Check if the current number i is Prime or not */ isPrime = 1; for(j=2; j<=i/2 ;j++) { if(i%j==0) { /* 'i' is not prime */ isPrime = 0; break; } } /* * If 'i' is Prime then add to sum */ if(isPrime==1) { sum += i; } } printf("Sum of all prime numbers between 1 to %d = %d", end, sum); return 0; }
Program to find sum of prime numbers in given range
/** * C program to find sum of prime numbers in given range */ #include <stdio.h> int main() { int i, j, start, end; int isPrime, sum=0; /* Input lower and upper limit from user */ printf("Enter lower limit: "); scanf("%d", &start); printf("Enter upper limit: "); scanf("%d", &end); /* Find all prime numbers in given range */ for(i=start; i<=end; i++) { /* Check if the current number i is Prime or not */ isPrime = 1; for(j=2; j<=i/2 ;j++) { if(i%j==0) { /* 'i' is not prime */ isPrime = 0; break; } } /* * If i is Prime then add to sum */ if(isPrime==1) { sum += i; } } printf("Sum of all prime numbers between %d to %d = %d", start, end, sum); return 0; }
Output
Enter lower limit: 10
Enter upper limit: 20
Sum of all prime numbers between 10 to 20 = 60