• # Program to convert the given string using recursion.

Have a query about writing recursion based C program? Interested in scoring well in C programming language exam? Go through the responses from ISC experts here and get the answer you are looking out for.

Following is a question that was asked in the MSBTE (Maharashtra State Board of Technical Education, Mumbai) Diploma in Electronics Engineering sample question paper of C Programming Language(22218).

This question is asked for 04 marks and hence requires some explanation along with the program code. Please let me know the solution.

Q) Write a C Program to convert the given string "Hello" to "olleH" using resursion.[4 Marks]

• The following code is a program to reverse a string using recursion in C programming language:
`# include void reverseString(char *strg) { if (*strg) { reverseString(strg+1); printf("%c", *strg); } } int main() { char a[] = "Hello"; reverseString(a); return 0; }`
Output : olleH

In the above code, the function reverseString is used to reverse the given string using recursion. The function takes the given string pointer as input and calls itself with the next address of the passed string since it's passed as a character array. Recursion continues till the array reaches its end ('\0') and the output is returned from the stack one by one.

“It takes a great deal of bravery to stand up to our enemies, but just as much to stand up to our friends."
– Albus Dumbledore, Harry Potter and the Sorcerer's Stone, Chapter 17

• Recursion:- Recursion is a process in which function calls itself until the base condition is true. Below I am taking one example to explain the process of recursion.
#include
int calculateFactorial(int n)
{
if(n >= 1)
{
return n * calculateFactorial(n - 1);
}
else
{
return 1;
}
}
int main(void) {
int num = 5, factorialOfNum;
factorialOfNum = calculateFactorial(num);
printf("Factorial of 5 is:- %d", factorialOfNum);
return 0;
}
Explanation:- This above program is for calculating the factorial of 5 by using the recursion.
As we know the definition of recursion that function call itself till the base condition is true, Here base condition is n>=1. So if this condition met this is going to call itself until this condition is wrong.

Below is my code to reverse the string by using recursion:-

#include
#include
void revOfStr(char*, int, int);
int main()
{
char strArray[] = "Hello";
revOfStr(strArray, 0, strlen(strArray)-1);
printf("Reverse of user string is:- %s",strArray);
return 0;
}
void revOfStr(char *str, int start, int end)
{
char ch;
if (start >= end)
{
return 1;
}
ch = *(str+start);
*(str+start) = *(str+end);
*(str+end) = ch;
revOfStr(str, ++start, --end);
}