8.08.2012

Print prime number 1 to 100

Q. Write a C program to accept a specific last number and print all the less then or equal prime number.
or
Q. Write a C program to print the prime number between 1 to n number.
for example: 1 to 100

Ans.

Note:-
1. 1 is not the prime number.
2. All even number is not the prime number except the number 2.

/*C program to print 1 to 100 prime numbers*/
#include<stdio.h>
#include<conio.h>
int main()
{
 int num,n,div,p;
 printf("Enter any number: ");
 scanf("%d", &num);
 for(n=2; n<=num; n++)
 {
  for(div=2; div<n; div++)
  {
   if(n%div==0)
   {
     p=0;
     break;
   }
   p=1;
  }
  if(p)
    printf("\t%d",n);
 }
 getch();
 return 0;
}

/************Output************/


Output of print 1 to 100 prime number C program
Screen shot for print the prime number
between 1 to 100 C program

Related program:

  1. Generate first n prime number C program
  2. Search for prime number C program
  3. Flowchart for search prime number

17 comments:

  1. Can u explain the program with example please.

    ReplyDelete
  2. the above program for(div=1;div<n;div++)
    then you get correct output

    ReplyDelete
  3. Thank U Dinesh Bera..,
    Finding prime numbers in this way helped me a lot in debugging my Assembly Code for finding N prime numbers... :)

    ReplyDelete
  4. I cannot understand the if else condition you used in prime number program

    ReplyDelete
  5. Formulate a model for picking out the prime number from this range and describe the input, processing and output intend in an algorithm to display all the prime numbers between 1 and 100?

    I need urgent answers please.

    ReplyDelete
  6. What about 2 .. it will not print 2 ..??

    ReplyDelete
  7. in the beginning of the program if you write p=1; then output will be show 2 also...
    i.e int num,n,div,p=1;

    ReplyDelete
  8. int num,n,div,p=1; this is the 100% right.....then output will be show 2 also

    ReplyDelete
  9. u can think better trick than this ... little bit confusing but will give us output...

    ReplyDelete
  10. Ah lao mitron shat partishat working code prime numbers da. The code is little bit lengthier but very clear and simple to understand.
    ---------------------------------------------------------------
    #include

    int main()
    {
    int a[500],n,k=0;
    cout << "Program to generate prime numbers" << endl;
    cout << "Enter upto which number you wish to generate prime numbers: ";
    cin>>n;
    if(n==1||n<1)
    cout<<"Invalid input";
    else if (n==2)
    cout<<"List of prime numbers: 2";
    else if (n==3)
    cout<<"List of prime numbers: 2 3";
    else if (n>3)
    {
    for(int i=4;i<=n;i++)
    {
    int j=2;
    while(j<=i/2)
    {
    if(i%j==0)
    {
    break;
    }
    else if (j==i/2&&i%j!=0)
    {
    a[k++]=i;
    }
    j++;
    }
    }
    cout<<"List of prime numbers: 2 3 ";
    for(int l=0;l<k;l++)
    {
    cout<<a[l]<<" ";
    }
    }

    return 0;
    }

    ReplyDelete