Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this function not returning a char data type?

//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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading