Program for Sum of Prime Numbers

Sum of Prime Numbers

We will write a C program sum of prime numbers and the number will be entered by the user. This will help to understand the basic structure of programming. In this program , we will display the calculation of sum of prime numbers easily by using proper syntax and algorithms.

Program for Sum of Prime Numbers

Working of Program :

In the program, we will require some numbers from the user to display the calculation of sum of prime numbers.

Important Note :

  • The number is a prime number which is greater than 1 and that is not a product of two smaller natural numbers
  • The number which is divisible by one and itself also referred to as prime number.

Syntax for For() Loop:-

for(Initialization,Condition,Increment / Decrement)
{
    // Statements 
}

Problem 1

Write a program to calculate the sum of all prime number between 1 to n using for loop.

  • Firstly, we have to enter the number.
  • Then print the sum of prime numbers between 1 to n.

Code

Run
#include<stdio.h> 
int main()
{
    int val =17;
    for(int i=2; i < val; i++)
    {
        if(val%i ==0)
        {
            printf("Given Number %d is not prime number", val);
            return 0;
        }
    }
    printf("Given Number %d is a Prime Number", val);
    return 0;
}

Output

Given Number 17 is a Prime Number

Note:

In the following program we will display the calculation of sum of prime number using while() loop.

Syntax for while() Loop:-

while(condition)
{
    // Statements
    // Increment / Decrement
}

Problem 2

Write a program to calculate the sum of prime number between 1 to n using while loop.

  • Firstly, we have to enter the number.
  • Then print the sum of prime numbers.

Code

Run
#include<stdio.h>
int main()
{
    int val = 21, i=2;
    while(i * i < val) 
    {
        if(val%i ==0)
        {
            printf("Given Number %d is not prime number", val);
            return 0;
        }
        i++;
    }
    printf("Given Number %d is a Prime Number", val);
    return 0;
}

Output

Given Number 21 is not prime number

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription