132k views
5 votes
How to write a Cprogram to print all the prime numbers between 1and n where n is the value supplied by the users.

1 Answer

5 votes

Answer:

#include <stdio.h>

int main()

{

int i, j, n, prime;

printf("Enter till where we want to find prime number: ");

scanf("%d", &n);

for(i=2; i<=n; i++)

{

prime = 1;

for(j=2; j<=i/2; j++)

{

if(i%j==0)

{

prime = 0;

break;

}

}

if(prime==1)

{

printf("%d, ", i);

}

}

return 0;

Step-by-step explanation:

A number which is divisible by 1 and itself is called prime number. Here in the program we start by taking number from 1 to n , where n is the last number till which we are required to find prime numbers. Then we start the loop by taking two for loops one for running the numbers from 1 to n and the inner for loop to check whether the number is divisible other than 1 and itself. We take the current number as prime =1. If the number is still not divisible by number other than 1 and itself we consider that number to be prime and print it.

User Jakub Linhart
by
5.0k points