I am trying to call the functions so that it prints out if the array is a palindrome or not. Please tell me what I am doing wrong; it seems I am not passing the arguments correctly. If I made a mistake with the post, please let me know; I am fairly new to the website.
This is how the output is supposed to look:
This is what my output looks like:
This is my code:
#include <stdio.h>
void createReverseArray();
void printArray();
void compareArray();
int main()
{
int MyArray1[] = {1, 2, 3, 2, 1};
int MyArray2[] = {1, 2, 3, 4, 1};
int MyArray3[] = {1, 2, 3, 3, 2, 1};
int MyArray4[] = {1, 2, 3, 4, 2, 1};
int n = 5, i, j, n, temp;
createReverseArray(MyArray1[5]);
createReverseArray(MyArray2[5]);
createReverseArray(MyArray3[5]);
createReverseArray(MyArray4[5]);
compareArray(MyArray1[5]);
compareArray(MyArray2[5]);
compareArray(MyArray3[5]);
compareArray(MyArray4[5]);
printArray(MyArray1[5]);
printArray(MyArray2[5]);
printArray(MyArray3[5]);
printArray(MyArray4[5]);
}
int createReverseArray(int &a[], int n)
{
i = 0;
j = n - 1;
while(i<j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
return reverse = a[];
}
int compareArray(int &a[], int reverse)
{
if(a[] == reverse) {
printf("The array is a palindrome")
}
else {
return 0;
}
}
void printArray(&a[])
{
printf("Array elements are:%d", a[]);
compareArray(a[]);
}
I am not sure due to the amount of uncertainties I have with the provided code, but if your objective is simply to detect whether the array is a palindrome, it is exceedingly simple and can be done in a single function:
bool isPalindrome(int[] list, int size)
{
for(int k = 0; k < size / 2 - 1; k++)
if(list[k] != list[size - k - 1])
return false;
return true;
}
This will iterate half your array, comparing it to the second half and exiting the instant one value is not equal to its mirror.
As for the mistakes in your code, I might be able to point out some of the more obvious ones, for future reference:
createReverseArray(MyArray1[5])
.MyArray[5]
is the integer in the sixth position of MyArray
.i
and j
from main
being used in createReverseArray
. THIS DOES NOT WORK.if(a[] == reverse)
. No matter what you were trying to achieve, this will never give you a useful result.void createReverseArray();
and int createReverseArray(int &a[], int n)
. You should declare them wit the same arguments and return values or the compiler will not understand they're the same thing.