使用遞迴檢查陣列是否為迴文數的 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
廣告