Print all the prime numbers from 1 to n. Print all the sum of prime numbers from 1 to n.


Program to print all the prime numbers and the sum of all Prime numbers between 1 to N.

        Prime numbers are not divisible any number except 1 and itself. The first loop will hold the range and the second one will be used to check whether the number is prime or not. If a number is prime it will be printed and added to the sum variable.

        Know more about loops here Loops in C++


Code

#include<bits/stdc++.h>

using namespace std;


int main(){

    cout<<"Enter a number "<<endl;         //Requesting a number


    int n;          //variable to store entered number

    cin>>n;         //Reading input


    int sum=0;         //variable to store sum


    for(int i=1;i<=n;i++){          //Loop to hold a number


      int flag=0;         //flag for true false value


        for(int j=2;j<=i/2;j++){      // loop to check the number is prime or not

            if(i%j==0){

                flag=1;          //if number is prime set flag to 1

                break;

            }

        }

        if(flag==0){           // if number is prime add it

            cout<<i<<" ";

            sum=sum+i;

        }

    }

    cout<<endl;         //to print the complete sum in next line

    cout<<"The sum of prime numbers in a given range is: "<<sum<<endl;

    return 0;

}


Output

Enter a number 
12
1 2 3 5 7 11 
The sum of prime numbers in a given range is: 29

Post a Comment

0 Comments