Home > Mobile >  Why is this function not returning a char data type?
Why is this function not returning a char data type?

Time:11-18

//Prime function

#include <stdio.h>
#include <math.h>
char Premier(int N){
    int i;
    char notpremier="Nombre n'est pas premier"; //Number is prime
    char premier="Nombre est premier"; //Number isn't prime
    for(i=2;i<=sqrt(N);i  ){
        if(N % i==0){
            return notpremier;
        }
        else{
            return premier;
        }
    }
}
int main() {
    printf("%c",Premier(10));
    return 0;
}

However, when I choose to return an int data type, it works perfectly.

CodePudding user response:

For starters the function returns nothing if the user will pass a value less than 4.

Secondly you are trying to initialize objects of the type char with expressions of the type char * because the string literals used as right hand operands are converted implicitly to pointers.

Also the comments are invalid.

char notpremier="Nombre n'est pas premier"; //Number is prime
char premier="Nombre est premier"; //Number isn't prime

And you have to move the sub-statement of the else statement

    else{
        return premier;
    }

below the for loop.

At least you need to write

char * Premier(int N){

and

char * notpremier="Nombre n'est pas premier"; //Number isn't prime
char * premier="Nombre est premier"; //Number is prime

and

for(i=2;i<=sqrt(N);i  ){
    if(N % i==0){
        return notpremier;
    }
}

return premier;

But also take into account that 0 and 1 are not prime numbers. And the function parameter should have unsigned integer type as for example unsigned int instead of the signed integer type int.

And instead of returning a string literal the function should return an integer: 1 - the passed number is prime, 0 - the passed number is not prime.

  • Related