C program to find sum of all prime numbers between 1 to n

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.

Example:
Input: n=10
Output: Sum of all prime numbers between 1 to 10 = 2 + 3 + 5 + 7 = 17

Required knowledge:

Basic C programming, If else, For loop, Nested loops

Prime numbers:

Prime numbers are the positive integers greater than 1 that has only two divisors 1 and the number itself. Example: 2, 3, 5, 7, 11 are the first 5 prime numbers.

Before calculating sum of all prime numbers between 1 to n we must first know how to list all prime numbers between 1 to n in C.

Program:

/**
 * C program to find sum of all prime numbers between 1 to n
 */

#include <stdio.h>

int main()
{
    int i, j, n, isPrime, sum=0;

    /*
     * Reads a number from user
     */
    printf("Find sum of all prime between 1 to : ");
    scanf("%d", &n);

    /*
     * Finds all prime numbers between 1 to n
     */
    for(i=2; i<=n; i++)
    {

        /*
         * Checks if the current number i is Prime or not
         */
        isPrime = 1;
        for(j=2; j<=i/2 ;j++)
        {
            if(i%j==0)
            {
                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", n, sum);

    return 0;
} 

Note: For checking whether a number is Prime or not we just need to check that the number should not be divisible by any number between 2 to n-1. Apart from that you can also check between 2 to n/2. Since any number more than (n/2)+1 cannot be exactly divided by n except self n.

Output
X
_
Find sum of all prime between 1 to : 10
Sum of all prime numbers between 1 to 10 = 17



Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment