Contact Learn C
Copy

Program 23:To Print all prime number within the given number

Program 23:
 
#include<stdio.h>
main()
{
  int num,i,count=0,j;
  printf("Enter a number \n");
  scanf("%d",&num);
  printf("The Prime numbers upto %d are\n",num);
  for(i=1;i<=num;i++)
  {
    count=0;
    for(j=1;j<=i;j++)
    {
      if(i%j==0)
      {
        count++;
      }
    }
    if(count==2)
    {
      printf("%d\n",i);
    }
  }
}
Explanation:
  1. The Program starts with initializing
    • num → For storing the number to get all prime numbers between 1 and num
    • i,jtemporary variables
    • count → To count the number of divisors
  2. printf("Enter a number \n");
    scanf("%d",&num);
    To take value from user.Let us assume it be 8(num=8)
  3. The loop iterates from i=1 to 8 one by one.Then count is made zero for every iteration.
  4. Now j will iterate from 1 to i and checks if any prime number is there between 1 and i. For example: if it is 5th iteration then i =5
    • Iteration 1: Then the for loop j starts as j=1,jtrue then loop continues
      • if i%j → 5%1==0 which is true,
      • then count=1
    • Iteration 2: Then the for loop j starts as j=2,jtrue then loop continues
      • if i%j → 5%2==0 which is false,
      • then count remains same i.e. count=1;
    • Iteration 3: Then the for loop j starts as j=3,jtrue then loop continues
      • if i%j → 5%3==0 which is false,
      • then count remains same i.e. count=1;
    • Iteration 4: Then the for loop j starts as j=4,jtrue then loop continues
      • if i%j → 5%4==0 which is false,
      • then count remains same i.e. count=1;
    • Iteration 5: Then the for loop j starts as j=5,jtrue then loop continues
      • if i%j → 5%5==0 which is true,
      • then count=2
    • Iteration 6: Then the for loop j starts as j=6,jfalse then loop terminates
    • Now if count==2 → true then this will be the prime number so this number is printed i.e i=5 is printed.
  5. Like the above iteration it checks each and every value of i whether it is prime or not and if it is prime it will print else not.
Output:
Print all prime number within the given number
Donate

Download App and Learn when ever you want

Get it on PlayStore
Get it on Amazon App Store
Get it on Aptoide