-2

I'm trying write a program that check if the given number is odd or even and prime or not prime. It compiled without a problem but no results came out. I'm in need of some tips. Thanks in advance.

int data(int n) {
    int  i, count;
    count = 0;
    if (n % 2 == 0){
        printf("%d is even ", n);
    }
    if(n % 2 != 0){
        printf("%d is odd ", n);
    }
    while (i = 2, i <= n/2, i++){
        if (n % i == 0){
            count++;
            break;
        }
    }
    if (count == 0){
        printf("and prime\n");
    }
    else {
        printf("and not prime\n");
    }   
    return 0;
}

int main(){
    data(11);
    data(74);
    data(307);
    data(7402);
    data(9357);
    return 0;
}
J...S
  • 5,079
  • 1
  • 20
  • 35

1 Answers1

1

The cause for the error must be the while (i = 2, i <= n/2, i++). You probably wanted a for loop like

for(i = 2; i <= n/2; i++){

The value of i = 2, i <= n/2, i++ is the value of i++ because of the way the comma operator works. The result will be the result of the last expression.

Have a look here.

The expressions will be evaluated from left to right but the result of the right-most expression becomes the value of the total comma-separated expression.

Otherwise if you are intent on a while loop do

i=2;
while (i <= n/2){
     ........
     ........
     i++;
}

where i++ is the last statement in the loop.

J...S
  • 5,079
  • 1
  • 20
  • 35