Monday 2 July 2012

Prime number between 1 to 300 in C


Code -


//__Program to print all prime numbers from 1 to 300._

/* A number is said to be a prime number if it is greater than 1 and has exactly 2 divisors,
one is the number itself and other is 1 For Example - Among 1 to 6, 
2-4-5 are prime numbers */

//_________Including Header Files in the program__________

#include<stdio.h>

#include<conio.h>

//__________Mainly imported for getch() Function______________

int main()

 //__________Main Function from where the program execution starts____________

{
int number = 0, counter = 0,temp_counter = 0, temp = 0, display_newline = 0;

       //__________Variable Declaration and Initialization_____

printf("\n\n\t  ___ Program will display prime number between 1 to 300 ___");

printf("\n\n\n\tPrime Numbers -  ");

for(counter = 2; counter <= 300 ; counter ++)

//________Looping construct will run from 2 to 300__________

{
number = counter;

         //____Copying the value of counter to variable named number________

temp = 0;

for (temp_counter = 1 ; temp_counter < counter ; temp_counter++)
{

/* This looping construct will work one less time the number and will
check whether the given number is divisible by any number less than the original number,
 if it is divisible a variable named as temp will be incremented by 1.
*/

if ((number % temp_counter) == 0)
{
temp++;
}
}

if (temp == 1)
/*______As mentioned at the starting the number is a prime number if it is
 divisible by 1 and number itself and in the above for loop, it is checked
 whether the number is divisible by any number between 1 and (number - 1),
 so if temp is equal to 1 then it is a prime number */

{
printf("%d, ", number);
}

}

getch();

return 0;

//__return 0 tells the compiler that program has executed successfully without any error_

}

Follow Us on Facebook - Assignment Hub

No comments:

Post a Comment