💡Key Concept
Inductive Reasoning could be an efficient way of understanding recursive algorithms. Based on that understanding, It would be easier to make a code for those algorithms such as calculating fibonacci numbers.
⏱️Time Complexity
A simple recursive algorithm for finding the nth Fibonacci number has a time complexity of O(2^n). This is because the algorithm recursively calculates the Fibonacci number by calling itself twice for each input value.
int calculate_nth_fibonacci(int n) {
if (n == 1 || n ==2) {
return 1;
}
else {
return calculate_nth_fibonacci(n - 1) + calculate_nth_fibonacci(n - 2);
}
}
💡Key Concept
The greatest common divisor between two integers can be effectively calculated using the Euclidean algorithm and recursion".
int gcd(int m, int n) {
if (m < n) {
int temp;
temp = m;
m = n;
n = temp;
}
// to use modulo operator, some constraints occur
// 1. input should not be 0
// 2. need to swap if m is bigger than n
if (m % n == 0) {
return n;
}
else {
return gcd(n, m % n);
}
}
int gcd2(int p, int q) {
// Resolves constraints related to using modulo operator by calling gcd function
if (q == 0) {
return p;
}
else {
return gcd(q, p % q);
}
}
The functions below may not be very efficient, but it can be helpful for strengthening coding skills by applying the method of implementing every interation such as for and while using recursion.
#define _CRT_SECURE_NO_WARNINGS
#define SIZE 100
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int getStringLength(char* str) {
if (*str == '\0' || *str == '\n')
// when the string is ended
// count the actual characters exclude '\n'
return 0;
else {
return 1 + getStringLength(str + 1);
}
}
// 1. print the first character of the obtained string
// 2. recursively call the function with the rest of the string.
void printChar(char* str) {
if (*str == '\0') {
return;
}
else {
printf("%c", *str);
return printChar(str + 1);
}
}
// 1. recursively call the function with the rest of the string excluding the first character
// 2. finally print the first character of the original string.
void printCharReverse(char* str) {
if (*str == '\0') {
return;
}
else {
printCharReverse(str + 1);
printf("%c", *str);
}
}
int main() {
char* str = (char*)malloc(sizeof(char) * SIZE);
// use fgets to get space character
fgets(str, 100, stdin);
printf("%d", getStringLength(str));
printf("\n");
printChar(str);
printf("\n");
printCharReverse(str);
printf("\n");
}
// 1. match the target to the last element of the given array
// 2. do the recursive call till n gets lower than 0
int sequentialSearch(int data[], int n, int target) {
if (n < 0)
return -1;
else if (data[n - 1] == target) {
return n - 1;
}
else {
return sequentialSearch(data, n - 1, target);
}
}
int max(int a, int b) {
if (a >= b)
return a;
else
return b;
}
// recursively compare the last element with the maximum of the remaining elements.
int findMax(int data[], int n) {
if (n == 1) {
return data[0];
}
else {
return max(data[n - 1], findMax(data, n - 1));
}
}
Some algorithms that are effective when implemented using recursion
void printInBinary(int n) {
if (n < 2) {
printf("%d", n);
}
else {
printInBinary(n / 2);
// without returning value, the modification can be printed
printf("%d", n % 2);
}
}
bool isDisjoint(int m, int A[], int n, int B[]) {
if (m <= 0 || n <= 0) {
return true;
}
else if (A[m - 1] == B[n - 1]) {
return false;
}
// Since both arraies are sorted, when the last element of array A is greater than that of B,
// all elemnts of B are less than that element.
else if (A[m-1] > B[n-1]) {
return isDisjoint(m - 1, A, n, B);
}
else {
return isDisjoint(m, A, n - 1, B);
}
}
Properties of Recursive Functions:
1. Every iterative function can be transformed into a recursive function.
2. Recursive functions can make complex algorithms appear simpler.
3. However, overhead such as transferring parameters and activation frames exist."
Recursive functions can be more elegant and easier to understand in some cases, but they can also be less efficient and prone to stack overflow errors if not designed properly.
Additionally, while overhead does exist in recursive functions, this should not necessarily discourage their use, as the benefits of more readable and modular code can outweigh the costs.
Tips for Implementing Recursive Functions:
It is important to clearly explain the mission of the algorithm. To achieve this, we can adopt two techniques.
1.Suggest at least one base case:
A base case is necessary to stop the recursion. Without a base case, the function will keep calling itself indefinitely, leading to a stack overflow error.
2. Use explicit parameters:
Since the recursive function calls itself, it's important to describe the mission of the function in the signature. This can help to avoid confusion and ensure that the function is implemented correctly.
🏠Take-Home-Message
I was confused about when to use return keyword in the recusrive case. The answer is you use it when the function need a return value that is from the pervious recursive function.
For instacne, finding a Fibonacci number, you use the return value because the result uses previously calculated numbers. (Even returning true or false could be essential.) On the other hand, when just reversely printing the character in a string, you don't a need return value.
int binarySearch(int data[], int left, int right, int target) {
int mid = (left + right) / 2;
if (left > right) {
// Search is complete and target value was not found
return -1;
}
else if (target == data[mid]) {
// find the target
return mid;
}
else if (target < data[mid]) {
// check the left portion
return binarySearch(data, left, mid - 1, target);
}
else {
// check the right portion
return binarySearch(data, mid + 1, right, target);
}
}
bool twoSum(int data[], int begin, int end, int K) {
if (begin >= end) {
// do not allow to pick the same value for both
return false;
}
else if (data[begin] + data[end ] == K) {
return true;
}
else if (data[begin] + data[end] < K) {
return twoSum(data, begin + 1, end, K);
}
else {
return twoSum(data, begin, end - 1, K);
}
}
Wow, What a Excellent post. I really found this to much informatics. It is what i was searching for.I would like to suggest you that please keep sharing such type of info.Thanks get my ip number
If more people that write articles really concerned themselves with writing great content like you, more readers would be interested in their writings. Thank you for caring about your content. restroom rental las vegas
Relating to a short time ago begun a good webpage, the info everyone deliver on this website has got improved my family dramatically. Kudos meant for your whole point in time & job. iptv uk
Relating to a short time ago begun a good webpage, the info everyone deliver on this website has got improved my family dramatically. Kudos meant for your whole point in time & job. iptv uk
Great survey, I'm sure you're getting a great response. link slot gacor hari Ini turbo x500 slot gacor hari ini
Appreciate it intended for placing a really good document! I stumbled upon your blog perfect for the desires. Its full of superb in addition to very helpful threads. Sustain the favorable do the job! 010인증대행
With the 1XBONO25 code, new 1xBet users can claim a 100% bonus up to $130. Take advantage of this bonus and explore the world of sports betting or casino games with extra funds today. cuenta de bono 1xbet como funciona
Thanks a lot for the purpose of rendering up to date update versions about the challenge, I just await read through further. 부산 출장마사지
I havent any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us. slot777
Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share. demo slot terlengka
Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share. ดูบอลสด liveวันนี้
Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share. ทีเด็ดบอล69
Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share. slot gacor
Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share. toto slot
Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work.rajabandot
Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. sbobet
Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. slot demo
Hey what a brilliant post I have come across and believe me I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. https://heally.co.kr/
Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me. slot
Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me. 밤알바
Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with extra information? It is extremely helpful for me. 스포츠중계
Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though. slot
Wow, cool post. I'd like to write like this too - taking time and real hard work to make a great article... but I put things off too much and never seem to get started. Thanks though. slot online
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! situs slot terpercaya
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! slot online
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! situs toto link alternatif
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! سایت بت لانا کازینو
I found this is an informative and interesting post so i think so it is very useful and knowledgeable. I would like to thank you for the efforts you have made in writing this article. 카지노 분양
Hello There. I found your blog using msn. This is an extremely well written article. I will be sure to bookmark it and return to read more of your useful information. Thanks for the post. I’ll certainly comeback. 토토분양
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! toto
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! tototogel
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! toto
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! toto
You know your projects stand out of the herd. There is something special about them. It seems to me all of them are really brilliant! 토토사이트 경찰조사 후기
I would like to say that this blog really convinced me to do it! Thanks, very good post. boutique islamique en ligne en france
I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. slot asia hoki
geishatoto
toto
slot hoki asia
Slot Gacor 777
The post is written in very a good manner and it contains many useful information for me. judi bola parlay
The post is written in very a good manner and it contains many useful information for me. 안전놀이터
The post is written in very a good manner and it contains many useful information for me. 홈페이지 제작
The post is written in very a good manner and it contains many useful information for me. 토토커뮤니티
The post is written in very a good manner and it contains many useful information for me. Ostéopathe Rezé sportif
All the contents you mentioned in post is too good and can be very useful. I will keep it in mind, thanks for sharing the information keep updating, looking forward for more posts.Thanks warungbetting daftar situs slot gacor situs slot gacorpragmatic demo
Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know. 토토사이트추천
Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know. login situs toto
Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know. 토토커뮤니티
Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know. 해외축구중계
Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know. 토토사이트추천
I’ve been searching for some decent stuff on the subject and haven't had any luck up until this point, You just got a new biggest fan!.. 안산 룸싸롱
I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. bandar toto macau
I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. olxtoto slot
I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. togel online
I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. live sgp
I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. togel online
That i taken aback when using the exploration everyone intended to get this to selected present astounding. Terrific process! Fitness Coach Casselberry FL
thanks for this usefull article, waiting for this article like this again. slot online
thanks for this usefull article, waiting for this article like this again. slot gacor
thanks for this usefull article, waiting for this article like this again. situs toto slot
thanks for this usefull article, waiting for this article like this again. slot88
thanks for this usefull article, waiting for this article like this again. judi bola
thanks for this usefull article, waiting for this article like this again. slot online
thanks for this usefull article, waiting for this article like this again. slot jackpot
thanks for this usefull article, waiting for this article like this again. olxtoto link
thanks for this usefull article, waiting for this article like this again. situs olxtoto
thanks for this usefull article, waiting for this article like this again. daftar slot thailand
thanks for this usefull article, waiting for this article like this again. apk slot dana
thanks for this usefull article, waiting for this article like this again. slot dana
thanks for this usefull article, waiting for this article like this again. slot gacor thailand
thanks for this usefull article, waiting for this article like this again. live hk lotto
thanks for this usefull article, waiting for this article like this again. [Koi toto]https://tecsenhomecare.com/)
Nice to read your article! I am looking forward to sharing your adventures and experiences.boost wow classic koi toto togel online togel online
A very awesome blog post. We are really grateful for your blog post. You will find a lot of approaches after visiting your post.slot online gacor health plan consulting timber frames for sale prefabricated barndominium
It is my first visit to your blog, and I am very impressed with the articles that you serve. Give adequate knowledge for me. Thank you for sharing useful material. I will be back for the more great post.agenolx alternatif
Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side? !!!!!!THANKS!!!!!!
Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. toto togel
Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. olxtoto rtp
Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. prediksi totomacau
I have read your article couple of times because your views are on my own for the most part. It is great content for every reader.
I am constantly surprised by the amount of information accessible on this subject. What you presented was well researched and well written to get your stand on this over to all your readers. Thanks a lot my dear.
Thanks for this great post, i find it very interesting and very well thought out and put together. I look forward to reading your work in the future.miototo
I am constantly surprised by the amount of information accessible on this subject. What you presented was well researched and well written to get your stand on this over to all your readers. Thanks a lot my dear.
I am constantly surprised by the amount of information accessible on this subject. What you presented was well researched and well written to get your stand on this over to all your readers. Thanks a lot my dear. toto togel situs totositus totototo togel onlineolxtoto macau
Only strive to mention one's content can be as incredible. This clarity with your post is superb! Thanks a lot, hundreds of along with you should go on the pleasurable get the job done. toto togelsamuraitotoolxtoto link신용카드현금화 신용카드 현금화 수수료
This unique is a fantastic put up I just spotted using show it again. Suggest whatever I wanted to ascertain optimism through forthcoming you are likely to remain for the purpose of showing this terrific put up. Best iptv