0% found this document useful (0 votes)
51 views1 page

C Program: Sum of Primes

This C program uses a for loop to find the sum of all prime numbers between 1 and a user-input number n. It iterates from 2 to n, uses an inner loop to check if each number i is divisible by any number from 2 to i/2, and if i is prime it is added to the running sum variable. Finally, it prints the sum of all prime numbers between 1 and n.

Uploaded by

Gabriel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views1 page

C Program: Sum of Primes

This C program uses a for loop to find the sum of all prime numbers between 1 and a user-input number n. It iterates from 2 to n, uses an inner loop to check if each number i is divisible by any number from 2 to i/2, and if i is prime it is added to the running sum variable. Finally, it prints the sum of all prime numbers between 1 and n.

Uploaded by

Gabriel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

C program to find sum of all prime numbers between 1 to n using for loop.

C program to generate
sum of all primes between a given range.

#include <stdio.h>
int main()
{
int i, j, n, isPrime, sum=0;
/*
* Reads a number from user
*/
printf("Find sum of all prime between 1 to : ");
scanf("%d", &n);
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}

You might also like