使用递归检查数组是否为回文数的 C 程序
给定一个数组 arr[n],其中 n 是数组的大小,任务是使用递归找出数组是否为回文数。回文数是一个可以正读反读都一样的序列,例如:MADAM、NAMAN 等。
因此,要检查数组是否为回文数,我们可以从后向前遍历数组,例如:

在递归中,我们也必须更改开始和结束值,直到它们相等,或者当开始和结束的值不相等时退出并返回 false,表示给定数组不是回文数。
示例
Input: arr[] = { 2, 3, 4, 3, 2}
Output: Yes, the array is Palindrome
Explanation: the array is identical from start (2, 3, 4, 3, 2) and end (2, 3, 4, 3, 2).
Input: arr[] = {1, 2, 3, 4}
Output: No, the array is not Palindrome
Explanation: The array is not identical from start (1, 2, 3, 4) and end (4, 3, 2, 1).下面使用的方案如下:
我们将递归地执行以下步骤:
- 检查 arr[start] 是否等于 arr[end] 且 start < end
- 将 start 加 1,并将 end 减 1。
- 转到步骤 1。
算法
Start
In function int palindrome(int arr[], int start, int end)
Step 1-> If start >= end then,
Return 1
Step 2-> If arr[start] == arr[end] then,
Return palindrome(arr, start + 1, end - 1)
Step 3-> Else {
Return 0
In fucntion int main()
Step 1-> Declare and initialize an array arr[]
Step 2-> Declare and initialize n = sizeof(arr) / sizeof(arr[0]
Step 3-> If palindrome(arr, 0, n - 1) == 1 then,
Print "Yes, the array is Palindrome”
Step 4-> Else
Print "No, the array is not Palindrome”
Stop示例
#include <stdio.h>
// Recursive pallindrome function that returns 1 if
// palindrome, 0 if it is not
int palindrome(int arr[], int start, int end) {
// base case
if (start >= end) {
return 1;
}
if (arr[start] == arr[end]) {
return palindrome(arr, start + 1, end - 1);
} else {
return 0;
}
// Driver code
int main() {
int arr[] = { 1, 2, 0, 2, 1 };
int n = sizeof(arr) / sizeof(arr[0]);
if (palindrome(arr, 0, n - 1) == 1)
printf("Yes, the array is Palindrome
");
else
printf("No, the array is not Palindrome
");
return 0;
}输出
如果运行上述代码,它将生成以下输出:
Yes, the array is Palindrome
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP