Palindromic numbers in C

Asked

Viewed 439 times

0

I need to create an algorithm that checks whether a number is palindromic or not. I decided to do this algorithm using a number as a string, but the program always returns that the numbers are not Palindromes.

char numero[10], numeroInvertido[10];
int i, j;

printf("Digite um numero : ");
scanf("%s",numero);

for (i = 0, j = 0; i < strlen(numero); i++, j++){
    numeroInvertido[j] = numero[i];
}

if (numeroInvertido == numero)
    printf("E um palindromo \n");
else
    printf("Nao e um palindromo \n");
  • https://answall.com/q/448607/101

  • 1

    Comparing strings in C is not done through the operator == and yes with the function strcmp of <string.h>. In addition a string must always contain the terminator character ' 0'. In reality its comparison is checking whether the address of numeroInvertido is equal to the address of numero.

1 answer

1

I made some modifications to your code, I believe even after solving the comparison, the program nay was generating the inverted number. I treated those and here’s the result:

#include <stdio.h>
#include <string.h>

int main(int argc, char const *argv[]) {
  char numero[10], numeroInvertido[10];
  int i, j;

  printf("Digite um numero : ");
  scanf("%s", numero);

  for (i = 0, j = strlen(numero) - 1; i < strlen(numero); i++, j--) {
    numeroInvertido[j] = numero[i];
  }

  if (!(strcmp(numeroInvertido, numero)))
    printf("E um palindromo \n");
  else
    printf("Nao e um palindromo \n");

  return 0;
}

Results:

Digite um numero : 12321
E um palindromo
Digite um numero : 1234
Nao e um palindromo

Browser other questions tagged

You are not signed in. Login or sign up in order to post.