Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to reverse a string using recursion in C

3 Answers

0 votes
#include <stdio.h>
#include <string.h>
 
void reverse_recursion(char s[], int index, int size) {
    char tmp;
     
    tmp = s[index];
    s[index] = s[size - index];
    s[size - index] = tmp;
     
    if (index == size / 2) {
        return;
    }
    
    reverse_recursion(s, index + 1, size);
}
 
int main(void) {
    char s[16] = "C programming";
 
    reverse_recursion(s, 0, strlen(s) - 1);
     
    puts(s);
 
    return 0;
}

 
 
/*
run:
 
gnimmargorp C
 
*/

 



answered Jan 16, 2021 by avibootz
edited Apr 26, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
 
char* reverse_recursion(char* s) {
    char tmp;
 
    if (strlen(s) <= 1) {
        return s;
    }
 
    tmp = *s;
    strcpy(s, reverse_recursion(s + 1));
    *(s + strlen(s)) = tmp;
 
    return s;
}
 
int main(void) {
    char s[16] = "C programming";
     
    reverse_recursion(s);
 
    puts(s);
 
    return 0;
}

 
 
/*
run:
 
gimmmargorp C

*/

 



answered Jun 2, 2023 by avibootz
edited Apr 26, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
 
char* reverse_recursion(char s[], int index, int size) {
    if(index < size && size > 1) {
        char temp = s[index];
        s[index] = s[size - 1];
        s[size - 1] = temp;
 
        reverse_recursion(s, ++index, --size);  
    }
}
 
int main(void) {
    char s[16] = "C programming";
     
    reverse_recursion(s, 0, strlen(s));
 
    puts(s);
 
    return 0;
}


 
 
/*
run:
 
gimmmargorp C

*/

 



answered Apr 26, 2024 by avibootz

Related questions

...