a program in c with detail explanation  to calculate the sum of all prime numbers between two given numbers using a for loop.

Program Source Code
Here is the source of a C program to count prime numbers in a range.
The C program given below compiles and runs successfully .
The program implementation is also shown below.


a C program to count prime numbers in a range

#include <stdio.h> #include <stdlib.h> int main() { int n1,n2,i, ,flag,temp,count=0; printf("\nEnter the value of n1 and n2 \n"); scanf("%d %d", &n1,&n2); if (n2<2) { printf("\nThere are no primes numbers upto %d",n2); exit(0); } printf("\nPrime numbers are:"); temp = n1; if (n1%2==0) { n1++; } for (i=n1;i<=n2;i=i+2) { flag=0; for (j=2;j<=i/2;j++) { if((i%j)==0) { flag = 1; break; } } if(flag==0) { printf("%d\n",i); count++; } } printf("\n Prime Numbers between %d and %d = %d\n", temp, n2, count); return(0); }

Program Explanation
1. The user has to take the range as input and it is stored in variables n1 and n2 respectively.
2. First check whether the number n2 is less than 2 or not. If it is then print the output as “There are no prime numbers”.
3. If it is not then check whether n1 is even. If the number is even then make it odd by incrementing the n1 by 1.
4. Using a for loop, starting from n1 to n2, check if the current number is divisible by any of the natural numbers starting from 2. Use one more for loop to do this Increment the first for loop by 2, so as to check the odd numbers.
5. First, initialize the variable flag and count to zero.
6. Use a variable flag to distinguish between prime and non-prime numbers, and use a count variable to count the number of primes in the range.
7. Print the prime numbers and the count of variables separately as output.
Runtime Test Cases
Case:1
Enter the value of n1 and n2
70 85
Prime numbers are
71
73
79
83
Prime Numbers between 70 and 85=4


Previous :-->> 17. Write a program in c to check if a given number is a perfect number or not using a do while loop.
 -->> NEXT: 19.Write a program in c language to print the pattern of a right angled triangle using a for loop.
-->>ALL Loops Assignments in c