ash22 ash22 - 1 year ago 64
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;
printf("enter a number");
scanf("%d", &a);
n > 1;
a != n && n < a;
if (a / n == x)
printf("a is not a prime no");
printf("a is a prime no");

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

Answer Source

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: ");
    for(n=2; n<=a/2; ++n)
    if (x==0)
        printf("a is not a prime no");    
    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download