Slider

C Program to Reverse Given String.

In this C programming tutorial, we are going to learn multiple ways to reverse the given String. Reverse String Using Loop. Reverse String Using Recur
Reversing a string is a process of arranging the character of the string in opposite directions. In this C programming tutorial, we are going to learn multiple ways to reverse the given String.

Example:
Input: str = Algolesson
Output: nosseloglA

Input: str = GoodCode
Output: edoCdooG

Reverse String Using Loop.

In this approach, we will reverse a string by using a loop that will iterate through the characters of the original string and build the reversed string character by character.

Below is the C implementation to reverse the string using for loop:
// C program to reverse the given string 
#include <stdio.h>
#include <string.h>

// function to reverse string
void reverseString(char str[]) {
    int length = strlen(str);
    for (int i = 0; i < length / 2; i++) {
        char temp = str[i];
        str[i] = str[length - i - 1];
        str[length - i - 1] = temp;
    }
}

int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%s", str);

    reverseString(str);

    printf("Reversed string: %s\n", str);

    return 0;
}
Output:
Enter a string: Algolesson
Reversed string: nosseloglA

Time Complexity: O(n)
Space Complexity: O(1)

Reverse String Using Recursion.

In this approach, we are going to use Recursion to reverse the given string. 

Below C code implementation:
// C program to reverse the given string using recursion
#include <stdio.h>

void reverseString(char str[], int start, int end) {
    if (start >= end) {
        return;
    }
    char temp = str[start];
    str[start] = str[end];
    str[end] = temp;
    reverseString(str, start + 1, end - 1);
}

int main() {
    char str[100];
    printf("Enter a string: ");
    scanf("%s", str);

    int length = strlen(str);
    reverseString(str, 0, length - 1);

    printf("Reversed string: %s\n", str);

    return 0;
}
Output:
Enter a string: Welcome
Reversed string: emocleW

In the recursive function, start and end represent the indices of the characters that need to be swapped. The function keeps swapping characters and recursively calling itself with the updated indices until the base case is reached.

Time Complexity: O(n)
Space Complexity: O(1)
0

No comments

Post a Comment

both, mystorymag

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson
Table of Contents