Examples of C part 23 all prime number till given number

#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);
    }
  }
}
Output:
Enter a number
30
The Prime numbers upto 30 are
2
3
5
7
11
13
17
19
23
29
Explanation:
  1. The Program starts with initializing
    • num → For storing the number to get all prime numbers between 1 and num
    • i,j → temporary 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,j → true 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,j → true 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,j → true 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,j → true 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,j → true 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,j → false 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.