CS201 Assignment 1 Solution Spring 2017

Assignment

Write a program that will ask the user to enter lower limit and upper limit in form of integers. The program will calculate and show the prime numbers within the range from lower limit to upper limit. All the prime numbers within the specified range should be displayed on the output. The program should also aggregate all the prime numbers within the range and show their sum as well. Also show the total number of prime numbers within the specified range.

Make sure that the user should not be able to enter a negative value or a value less than 2. Also the value entered as lower limit should not be greater than the upper limit.

Solution :

#include <iostream>
using namespace std;
int main(){
int i,j,l,u;
int r=0,sum=0,c=0;
std::
cout<<“Enter The Lower Limit : “;
std::
cin>>l;
std::
cout<<“Enter The Upper Limit : “;
std::
cin>>u;
if(l>=u){std::
cout<<“\nLower Limit can not be greater than or equal to the upper limit!”;
}
else if(l<=1){
std::
cout<<“\nLower Limit can not be less than 2”;
}
else{
std::
cout<<“\nPrime numbers between the range are:\n”;
for(i=l;i<=u;i++){
for(j=2;j<i;j++){
if(i%j==0){
r++;}
}
if(r==0){
std::
cout<<i<<“\t”;
sum=sum+i;
c++;
}
r=0;
}
std::
cout<<“\n\nTotal numbers between the range are:”<<c;
std::
cout<<“\nSum of prime numbers between the range is:”<<sum;
}

}