160k views
3 votes
Write a ' C ' program to to accept ' n ' integers in array. Write a function which will return 1 if the array is 'Palindrome' and 0 if not. Note: examples of Palindrome: [2, 3, 2],[1,2,2,1] (Use malloc, function and pointer)

1 Answer

1 vote

Final answer:

To check if an array is a palindrome in C language, you can create a function that reverses the array and then compare it with the original array. If they are identical, the array is a palindrome. Otherwise, it is not.

Step-by-step explanation:

To write a program in C language that determines whether an array is a palindrome or not, you can follow the steps below:

  1. Define a function that takes an array of integers as input.
  2. Allocate memory for a new array with the same size as the original array.
  3. Reverse the elements of the original array and store them in the new array.
  4. Compare each element of the original array with the corresponding element of the reversed array.
  5. If all elements are the same, return 1 (indicating that the array is a palindrome), otherwise return 0.

Here's an example implementation:

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

int isPalindrome(int *array, int size) {
int *reversedArray = (int *) malloc(size * sizeof(int));

for (int i = 0; i < size; i++) {
reversedArray[i] = array[size - 1 - i];
}

for (int i = 0; i < size; i++) {
if (array[i] != reversedArray[i]) {
free(reversedArray);
return 0;
}
}

free(reversedArray);
return 1;
}

int main() {
int n;
printf("Enter the number of integers in the array: ");
scanf("%d", &n);

int *array = (int *) malloc(n * sizeof(int));
printf("Enter the integers: ");
for (int i = 0; i < n; i++) {
scanf("%d", &array[i]);
}

int result = isPalindrome(array, n);
if (result) {
printf("The array is a palindrome.");
} else {
printf("The array is not a palindrome.");
}

free(array);

return 0;
}
User Sudha
by
8.0k points