Q:

Prime Number Program In C (3 Simple Ways)

belongs to collection: Basic C Programming Examples

0

you have to make this program in the following way:

  • Prime Number Program In C Using For Loop
  • Prime Number Program In C Using While Loop
  • Prime Number Program In C Using Do While Loop

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Prime Number Program In C Using For Loop

Algorithm

  • Program start
  • Declare Variable
  • Loop start
  • Check if condition
  • Desplay result According to Condition
  • Program End

Program

//C  Program to check prime number Using For loop

#include <stdio.h>
int main()
{

   int n, i, count = 0;

    printf("Enter a number to check prime number or not : ");
    scanf("%d",&n);

    for(i=2; i<n; ++i)
    {
        // check for non prime number
        if(n%i==0)
        {
            count=1;
            break;
        }
    }
    if (count==0)
        printf("%d is a prime number.",n);
    else
        printf("%d is not a prime number.",n);
}

Output

Enter a number to check prime number or not : 5
5 is a prime number.

Prime Number Program In C Using While Loop

Program

//C Program for Prime Number Using While Loop

#include <stdio.h>
int main()
{

   int n, i = 2, count = 0;

    printf("Enter number to check prime number or not : ");
    scanf("%d",&n);

    while(i<n)
    {
        // check for non prime number
        if(n%i==0)
        {
            count=1;
            break;
        }
        i++;
    }
    if (count==0)
        printf("%d is a prime number.",n);
    else
        printf("%d is not a prime number.",n);
}

Output

Enter number to check prime number or not : 17
17 is a prime number.

Prime Number Program In C Using Do While Loop

Program

//C program to check prime number using do while loop

#include <stdio.h>
int main()
{
   int n, i = 2, count = 0;

    printf("Enter a number to check prime number or not : ");
    scanf("%d",&n);

    do
    {
        // check for non prime number
        if(n%i==0)
        {
            count=1;
            break;
        }
        i++;
    }while(i<n);
    if (count==0)
        printf("%d is a prime number.",n);
    else
        printf("%d is not a prime number.",n);
}

Output

Enter a number to check prime number or not : 9
9 is not a prime number.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Basic C Programming Examples

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Armstrong Number Program In C (5 Different Way To ... >>
<< Odd or Even Program In C (7 Different Ways)...