Reputation: 49
I need help in one of my project for the accademy. I need to code an algorithm to find palindrome number from the six digits that the user will decide to write. There are some limitation for me, the number needs to be 6 digits long, the code must contain function that will calculate the given number and the number needs to be in array. I will attach my algorithem so far if someone can help me figure up why it does not working. Thank you guys!
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS
#define N 6
int palindrome(int rev_arr[N], int arr[N]);
int palindrome(int rev_arr[N], int arr[N])
{
int i = 0, j = 0;
int a = 0;
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
{
arr[i] = rev_arr[j];
}
}
for (i = 0; i < N; i++)
{
for (j = N; j >= 0; j--)
{
if (arr[i] == rev_arr[j])
{
a = 1;
}
else
{
a = 0;
}
}
}
return a;
}
void main()
{
int i = 0, arr[N], rev_arr[N], j = 0, p1 = 0, a = 0;
printf("Please enter your six digit's number:\n");
for (i = 0; i < N; i++)
{
scanf("%d", &arr[i]);
}
p1 = palindrome(rev_arr[N],arr[N]);
if (p1 == 1)
{
printf("The number is palindrome! :)\n");
}
else if (p1 == 0)
{
printf("The numbe is not palindrome! :(\n");
}
}
Upvotes: 1
Views: 75
Reputation: 387
Instead of scanning all array len you can stop to its middle len:
int palindrome(int arr[N])
{
int i = 0, end = N / 2;
for (i = 0; i < end; i++)
{
if (arr[i] != arr[N-i-1])
return 0;
}
return 1;
}
Pay attention also that correct call to palindrome
function is palindrome(arr)
and not palindrome(arr[N])
.
So you can check if a sequence is palindrome by doing:
if (palindrome(arr))
printf("The number is palindrome! :)\n");
else
printf("The numbe is not palindrome! :(\n");
Upvotes: 2