เราได้รับสตริงหนึ่งตัว ให้เรียกว่า str ความยาวเท่าไหร่ก็ได้ และงานคือคำนวณจำนวนพยัญชนะในสตริงที่กำหนดโดยใช้ทั้งวิธี iterative และ recursive
พยัญชนะคือตัวอักษรที่ไม่ใช่สระ คือ ตัวอักษรยกเว้น a, i, e, o, u ถือเป็นพยัญชนะ ดังนั้นในโปรแกรมด้านล่างเราต้องหาจำนวนตัวอักษรที่ไม่ใช่สระในสตริง
Recursion และ Iteration ทั้งคู่วนซ้ำชุดคำสั่ง Recursion คือเมื่อคำสั่งในฟังก์ชันเรียกตัวเองซ้ำ Iteration คือเมื่อลูปวนซ้ำจนเงื่อนไขควบคุมเป็นเท็จ ความแตกต่างหลักคือ recursion เป็นกระบวนการใช้กับฟังก์ชัน ส่วน iteration ใช้กับชุดคำสั่งที่ต้องการให้ทำซ้ำ
ตัวอย่าง
อินพุต – string str = "tutorials point" เอาต์พุต – count is 8
คำอธิบาย – ในสตริง str ที่กำหนด มีพยัญชนะทั้งหมด 8 ตัว คือ t, t, r, l, s, p, n, t
อินพุต – string str = "a e io u" เอาต์พุต – count is 0
คำอธิบาย – ในสตริง str ที่กำหนด ไม่มีพยัญชนะ มีแต่สระ ดังนั้น count คือ 0
วิธี Iteration
วิธีการที่ใช้ในโปรแกรมด้านล่าง
- รับสตริงในตัวแปร str
- คำนวณความยาวของสตริงด้วย length() จะคืนค่า integer ตามจำนวนตัวอักษร
- ใช้ตัวแปรชั่วคราวเก็บจำนวนองค์ประกอบ
- เริ่มลูป for i จาก 0 ถึง i น้อยกว่าความยาวของสตริง
- ในลูป ตรวจสอบ IF str[i] เป็นพยัญชนะ แล้วเพิ่มค่า count ขึ้น 1
- คืนค่า count
- พิมพ์ผลลัพธ์
ตัวอย่างโค้ด Iterative
// Iterative CPP program
#include <iostream>
using namespace std;
bool consonant(char ch){
ch = toupper(ch);
return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90;
}
int countconsonants(string s){
int result = 0;
for (int i = 0; i < s.length(); i++){
if (consonant(s[i])){
++result;
}
}
return result;
}
int main(){
string s = "wx abc def";
cout << "count is: " << countconsonants(s);
return 0;
}เอาต์พุต
count is: 6
วิธี Recursive
วิธีการที่ใช้ในโปรแกรมด้านล่าง
- รับสตริงในตัวแปร str
- คำนวณความยาวของสตริงด้วย length()
- ใช้ตัวแปรชั่วคราวเก็บจำนวนองค์ประกอบ
- สร้างฟังก์ชัน recursive ที่เรียกตัวเองเพื่อคำนวณพยัญชนะในสตริง
- ตรวจสอบ IF size เป็น 1 คืนค่า str[0]
- จากนั้น คืนค่า recursive_call(str, size-1) + ตรวจสอบว่าตัวอักษรเป็นพยัญชนะหรือไม่ (str[size-1])
ตัวอย่างโค้ด Recursive
// Recursive CPP program
#include <iostream>
using namespace std;
bool consonant(char ch){
ch = toupper(ch);
return !(ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') && ch >= 65 && ch <= 90;
}
int consonantcount(string str, int n){
if (n == 1){
return consonant(str[0]);
}
return consonantcount(str, n - 1) + consonant(str[n-1]);
}
int main(){
string str = "wx abc def";
cout << "count is: " << consonantcount(str, str.length());
return 0;
}เอาต์พุต
count is: 6