Wednesday, 8 November 2017

Write a C program that will find the sum of all prime numbers in a given range. The range will be specified as command line parameters. The first command line parameter, N1 which is a positive integer, will contain the lower bound of the range. The second command line parameter N2, which is also a positive integer will the upper bound of the range. The program should consider all the prime numbers within the range, excluding the upper and lower bound. Print the output in integer format to stdout. Other than the integer number, no other extra information should be printed to stdout.

Example: Given input "7" and "24" here N1=7 and N2=24, expected output as 83

#include<stdio.h>
int main(int argc,char *argv[])
{
int N1,N2,i,j,sum=0,count,lower,upper;
if(argc!=3)
exit(0);
N1=atoi(argv[1]);
lower=N1+1;
N2=atoi(argv[2]);
upper=N2;
for(i=lower;i<upper;i++)
{
count=1;
for(j=2;j<=i/2;j++)
{
if(i%j==0)
{
count++;
}
}
if(count==1)
{
sum=sum+i;
}
}
printf("%d",sum);
return 0;
}

Output :

1. why this if condition has to be added?

if(argc!=3)
exit(0);

1. Because while running we have to write
ProgramName 7 24
As we have to pass 3 agruments (one for program-name, one for lower range and one for the upper range )
so, if the passed argument is other than 3 then it will terminate execution
Example: programName 7 Don't need to be run as it has just lower range but not upper range

2. did anyone get this program?

3. As you mentioned in the question N1, N2
Why don't you use N2 in the program???

1. previously I have written N2 as "upper" because name of variable doesn't matter, but for your convenience I have changed it to N2.

4. can i have this program in basic c

Featured Post

TCS Latest Test Patern ( For On-Campus Drives )

Tata Consultancy Services is software services consulting company whose  headquarter is situated in Mumbai, India. It is the Asia’s larges...