September 14, 2010
Recursive Upper Function
Problem
Write a C++ recursive function to convert a character string into capital letters.
Solution
Instead of looping in the string character by character we can recursively call a function while advancing an index each time. Once the index reaches the end of the string we stop recursion. Converting a letter into capital case in C++ is simply achieved by adding the difference between any capital letter and its small letter ASCII value to the ASCII code of the character that we need to convert. Please refer to the code below for more details.
Code
Here is the C++ code to do that
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
//Includes #include <iostream> //STD using namespace std; //Parameters: input string, //character index, string size char* RecursiveUpper(char str[], int i, int n) { //Convert character to CAPS //only if it is a small letter if (str[i] >= 'a' && str[i] <= 'z') { //To convert a character into capital //letter case add to its ASCII value //the difference between A and a str[i] += 'A'-'a'; } //Stop when i = n-1 if (i == n-1) { return str; } //Advance index (i) then call again RecursiveUpper(str, i+1, n); } //Main function void main() { char str[] = "redfOx"; cout << RecursiveUpper(str, 0, 6) << endl; } |