Gibas Gibas - 27 days ago 5
C Question

Printf strange characters

Why it doesn't work? In the end of the program, it shows 2 strange characters instead of "e primo" or "nao e primo". I would be grateful if you could help me.

#include <stdio.h>
#include <stdlib.h>

int main() {
// var
int n, c = 2;
char p[11];
// code
printf("Informe um numero para checar se e primo: ");
scanf("%d", &n);
do {
if (n % c == 0) {
p[11] = 'e primo';
break;
} else {
p[11] = 'nao e primo';
}
c = c + 1;
} while (c != n / 2);
printf("\nO numero %s", p);
return 0;
}

Answer

Your program has some problems:

  • you cannot copy string with a simple assignment p[11] = 'e primo';. You could use strcpy() with a string if you make the buffer larger or you could just use a string pointer const char *p;.

  • The loop runs forever if n is less than 4. More precisely, it invokes undefined behavior when c = c + 1; causes arithmetic overflow.

  • The result is the exact opposite for other values.

  • The loop is very slow for large prime numbers, you should stop when c * c > n.

Here is a corrected version:

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    // var
    int n, c;
    const char *p = "e primo";
    // code
    printf("Informe um numero para checar se e primo: ");
    if (scanf("%d", &n) == 1) {
        for (c = 2; c * c <= n; c = c + 1) {
            if (n % c == 0) {
                p = "nao e primo";
                break;
            }
        }
        printf("O numero %s\n", p);
        return 0;
    }