Wednesday 12 September 2012

To print a prime numbers up to 1 to n


Description:
Prime number is a number which is exactly divisible by one and itself only
Ex: 2, 3,5,7,………;
Algorithm:
Step 1: start
Step 2: read n
Step 3: initialize i=1,c=0
Step 4:if i<=n goto step 5
                        If not goto step 10
Step 5: initialize j=1
Step 6: if j<=i do the following. If no goto step 7
                        i)if i%j==0 increment c
                        ii) increment j
                        iii) goto Step 6
Step 7: if c== 2 print i
Step 8: increment i
Step 9: goto step 4
Step 10: stop
 

 
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
   int n,i,fact,j;
   clrscr();
   printf("enter the number:");
   scanf("%d",&n);
   for(i=1;i<=n;i++)
   {
             fact=0;
 //THIS LOOP WILL CHECK A NO TO BE PRIME NO. OR NOT.
            for(j=1;j<=i;j++)
             {
                        if(i%j==0)
                         fact++;
             }
             if(fact==2)
            printf("\n %d",i);
    }
getch( );
}

Output:
Enter the number : 5
2        3  5
Enter the number : 10
2    3   5    7
Enter the number : 12
2    3   5    7,11

 Conclusion : The program is error free

VIVA QUESATIONS:
1)  What is prime number ?
Ans: Prime number is a number which is exactly divisible by one and itself only

  2)What is an algorithm?
Ans :  A step by step procedure is called algorithm

3)What is flow chart?
Ans:     A pictorial representation an  algorithm is called a flow chart
4)What is program?
Ans :  A collection of statements is called

1 comment: