AbsoluteSith
AbsoluteSith

Reputation: 1967

How to print reversal of a string without using inbuilt functions and loops in C?

I have come across this question in a programming contest, but couldn't find the answer can anyone please help me with this???

Input<<string
Output<<reverse(string)

constraints: No loops allowed,No inbuilt functions have to be used!

Upvotes: 0

Views: 9346

Answers (2)

cdhowie
cdhowie

Reputation: 169133

To give a concrete answer based on NPE's hint to use recursion, we need to use recursion for two things: finding the end of the string, and actually swapping everything.

Here is a complete program illustrating this approach (see it run):

#include <stdio.h>

char * find_end_of_string(char *str)
{
    return *str ? find_end_of_string(str + 1) : str;
}

void do_reverse_string(char *a, char *b)
{
    char tmp;

    if (a < b) {
        tmp = *a;
        *a = *b;
        *b = tmp;

        do_reverse_string(a + 1, b - 1);
    }
}

void reverse_string(char *str)
{
    do_reverse_string(str, find_end_of_string(str) - 1);
}

int main() {
    char odd[] = "abcde";
    char even[] = "abcdef";

    reverse_string(odd);
    reverse_string(even);

    printf("%s\n%s\n", odd, even);

    return 0;
}

Upvotes: 2

NPE
NPE

Reputation: 500585

Use recursion:

#include <stdio.h>

void print_reversed(const char* str) {
  if (*str) {
    print_reversed(str + 1);
    printf("%c", *str);
  }
}

int main() {
  print_reversed("abcdef");
  printf("\n");
}

Upvotes: 7

Related Questions