TASK-
Write a C program to find prime numbers in a range and their sum!!
CODE:
#include<stdio.h>
int main(){
int num,i,j,flag=1,sum=0;//flag is taken to identify prime number
printf("Enter the number ");
scanf("%d",&num);
for (i=2;i<=num;i++) // i start by 2 because 1 is not a prime number to make execution smaller we reduced 1 cycle;
{
flag=1;
for (j=2;j<=i/2;j++)
// If a number is not a prime it would be divided before the half of its value; j=2 because every number will be by 1 and
// will make flag=0
{
if (i%j==0)
{
flag=0;
break;
}
}
if (flag==1) // if flag remained 1 it means i%j is not equal to zero hence its a prime;
{
printf("\n%d is prime ",i);
sum=sum+i; // to calculate sum of prime numbers
}
}
printf("\nSum of all prime number from 1 to %d is %d",num,sum);
getchar();
return 0;
}
Expected Output:
brilliant !
ReplyDeleteExcellent information
ReplyDelete