ash22 ash22 - 3 months ago 9
C Question

what is wrong with this code? (to check whether a given number is a prime number)

#include <stdio.h>
#include <conio.h>

void main() {
int a, n, x;
clrscr();
printf("enter a number");
scanf("%d", &a);
n > 1;
a != n && n < a;
if (a / n == x)
printf("a is not a prime no");
else
printf("a is a prime no");
}


If I run this and put a composite number, it still shows it as prime.

Answer

your if statement is never true duo to n and x are not initialized. Therefore you only get your else as return. Moreover your expression n>1; and a != n && n < a; return a bool which is not compered to anything. In that case you need to use a for loop.

Here is a link About for loops

int main()
{
    int a,n,x = 0;

    printf("enter a number: ");
    scanf("%d",&a);
    for(n=2; n<=a/2; ++n)
    {
        if(a%n==0)
        {
            x=1;
            break;
        }
    }
    if (x==0)
        printf("",n);
    else
        printf("a is not a prime no");    
    return 0;
}