Saturday 11 November 2017

C Program to Reverse the String using Both Recursion and Iteration


Code:

#include
#include

/* Function Prototype */
void disp_str1_rec(char *);

void main()
{
    char str1[100], *ptr;
    int len1 = 0, i;
    char ch;
    printf("Enter the string:\n");
    scanf("%[^\n]s", str1);
    ptr = str1;
    len1 = strlen(str1);
    printf("Using iteration:\n");
    for (i = len1 - 1; i >= 0;i--)        /* Iterative loop */
    {

        ch = str1[i];
        printf("%c", ch);
    }
    printf("Using recurssion:\n");
    disp_str1_rec(ptr);
}

/* Code to reverse the string using Recursion */
void disp_str1_rec(char *stng)
{
    char ch;
    if (*stng != '\0')
    {
        ch = *stng;
        stng++;
        disp_str1_rec(stng);
        printf("%c", ch);
    }
    else
    return;
}

Output:

Enter the string:
welcome to  c programming class

Using iteration:
ssalc gnimmargorp c  ot emoclew
Using recurssion:
ssalc gnimmargorp c  ot emoclewi

More C Programs:













100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...