The Way to Programming
The Way to Programming
Let’s discuss the basic idea behind writing a C program to check whether the given number is a prime number or not.
If you want to learn C programming, then you must be knowing about the basics of C language and its syntax.
The C language is a general purpose programming language that is designed to be a portable assembler. The C language is widely used to develop applications that run on multiple operating systems.
So, let’s see how to write a C program to check whether the given number is a prime number or not.
To write a C program to check whether the given number is a prime number or not, you need to start with a simple function.
Here is the syntax of the function to check whether the given number is a prime number or not.
[dm_code_snippet background="no" background-mobile="no" slim="yes" bg-color="#abb8c3" theme="dark" language="clike" wrapped="no" height="" copy-text="Copy Code" copy-confirmed="Copied"]
int is_prime(int x);
[/dm_code_snippet]
Parameters:
[dm_code_snippet background="no" background-mobile="no" slim="yes" bg-color="#abb8c3" theme="dark" language="clike" wrapped="no" height="" copy-text="Copy Code" copy-confirmed="Copied"]
x – The number whose primality is to be checked.
[/dm_code_snippet]
Return Value:
The function returns either 0 if the given number is a prime number or 1 if the given number is not a prime number.
Sample Output:
Here is an example of a program to check whether the given number is a prime number or not.
Code:
[dm_code_snippet background="no" background-mobile="no" slim="yes" bg-color="#abb8c3" theme="dark" language="clike" wrapped="no" height="" copy-text="Copy Code" copy-confirmed="Copied"]
/*
Prime number Checker
*/
int is_prime(int x)
{
int i = 2, j = 2;
if (x == 1)
return 1;
while (i < sqrt(x))
{
if (x % i == 0)
return 0;
i++;
}
return 1;
}
int main()
{
int n, i, j;
printf("Enter the number to be checked for its primality: ");
scanf("%d", &n);
for (i = 2; i <= sqrt(n); i++)
{
j = 2;
while (j <= n/i)
{
if (is_prime(n - j*i))
break;
j++;
}
if (j == n/i)
printf("%d is a prime number.\n", n);
else
printf("%d is not a prime number.\n", n);
}
getch();
return 0;
}
[/dm_code_snippet]
Hope you learned about the basics of C programming and writing a C program to check whether the given number is a prime number or not.
Sign in to your account