💡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);
}
}
This may be a really good hints mainly that will the ones novices at blogosphere, shorter together with complete information… Kudos meant for posting ours. Extremely important look over report. https://svenskiptv.com
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
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
Incredible! Just what an eye fixed opener this kind of submit continues to be for me personally. Quite definitely treasured, book marked, My partner and i can’t watch for a lot more! iron pro tv
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
The Debox method initiates healing by confronting emotional traumas directly, facilitating a rapid emotional recovery. Through specific exercises, the method enables individuals to reframe traumatic memories, evidenced by case studies where participants reported significant stress reduction. The digital book available at https://debox.Co/debox-digital-book/ details these exercises along with step-by-step guidance. Studies have shown that users of the Debox method experience a notable decrease in symptoms of anxiety and depression, often within a few weeks of consistent practice. This approach incorporates techniques to dismantle the power of negative beliefs, replacing them with positive affirmations, as documented in multiple recovery narratives within the book. Engaging with the method requires no prior experience in mental health therapies, making it accessible to a broad audience. Participants report an average improvement in emotional wellbeing scores by over 60% after three months of application. The Debox method fosters resilience by teaching coping strategies that individuals apply in various stressful situations, for example, workplace challenges or personal loss. Feedback from users highlights a 75% increase in their ability to handle life stresses post-engagement with the method. For those seeking peer support, the book directs to community forums where thousands share their success stories and challenges, creating a supportive network. Importantly, this method aligns with scientific principles of neuroplasticity, allowing the brain to form new, healthier patterns of thought and behavior.trauma removal therapy Debox Method
The following is the perfect posting I actually found as a consequence of promote them. It's really just what exactly Needed to check out anticipation around long run you are going to continue on to get spreading this sort of great posting. 일수사이트
Good place, walked into the future together with bookmarked as their favorite your websites. That i can’t procrastinate to read the paper even more with everyone. slot gacor hari ini
With thanks to get furnishing recently available posts in connection with the dilemma, I actually look ahead to learn extra. situs slot88
Thanks for picking out the time to discuss this, I feel great about it and love studying more on this topic. It is extremely helpful for me. Thanks for such a valuable help again. 프라그마틱 슬롯
Great survey, I'm sure you're getting a great response. link slot gacor hari Ini turbo x500 slot gacor hari ini
Many thanks with regard to supplying current improvements concerning the issue, We anticipate study much more.bandar togel
Really special blog post, Thanks for your time designed for writing It education. Outstandingly drafted guide, if only every webmasters marketed the exact same a better standard of subject matter whilst you, cyberspace was obviously a better set. Satisfy continue the good work! mix parlay
Code promo 1xBet 2025 : Utilisez le code — 1X200FOX pour profiter d'une offre VIP de 100% jusqu'à 130€ sur les paris sportifs ou de 1950€ + 150 tours gratuits. Renseignez le code promo lors de la création de votre compte et obtenez un bonus sur les paris sportifs jusqu'à $130. Sur le casino vous pourrez bénéficier d'un bonus allant jusqu'à $1950 + 150 tours gratuits. code promo 1xbet maroc
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인증대행
1Win offers a 500% bonus up to $1025 with the 1WinMax500 code. Receive 70 free spins instantly, and enjoy no-verification-required bonuses along with daily promotions for added fun and rewards. 1win bonus code no deposit
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
Melbet 2025 offers a great opportunity with the "MEGA200" promo code. Get up to 200€ on your first deposit and enjoy a 130% bonus, making it the perfect way to start betting with more funds. comment avoir un code promo melbet
This is only the internet My organization is choosing all around you. Kudos in your webpage, We add your email your blog. This may be a fine webpage. . 트립닷컴 항공권 할인코드
Thank you for your submit and also fantastic suggestions.. also My partner and i furthermore believe work will be the main part of acquiring accomplishment. 슬롯사이트 후기
Extremely good, impressive, fact-filled material at this point. An individual's articles or blog posts Rarely dissatisfy, and therefore without doubt holds true at this point in the process. Everyone at all times result in a useful look over. Is it possible reveal to I will be astounded?: )#) Stick to the fantastic article content. https://animejolt.com
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
Claim the 1win promo code MAX500WIN and earn a 500% bonus up to $1025 on your first four deposits. This amazing offer is available for new users and existing players. Don’t miss out—grab your bonus today! bonus code for 1win
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! 토토사이트 경찰조사 후기
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. link alternatif miototo 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. situs toto alternatif 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. situs toto 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. daftar situs toto 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. Situs slot gacor
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
To be a Rookie, My business is for good researching on the net intended for articles or blog posts which might be connected with assistance to everyone. Appreciate it. Bijoux fabriqués au Québec