0% found this document useful (0 votes)
27 views3 pages

String Reverse

The document provides three different C programs to reverse a string. The first program uses a loop to swap characters, the second employs recursion to achieve the same result, and the third utilizes the library function 'strrev' for reversing. Each program demonstrates a unique approach to string manipulation in C.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views3 pages

String Reverse

The document provides three different C programs to reverse a string. The first program uses a loop to swap characters, the second employs recursion to achieve the same result, and the third utilizes the library function 'strrev' for reversing. Each program demonstrates a unique approach to string manipulation in C.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Write Program to Reverse String

#include <stdio.h>

#include <string.h>

void reverse(char* str) {

// Initialize first and last pointers

int first = 0;

int last = strlen(str) - 1;

char temp;

// Swap characters till first and last meet

while (first < last) {

// Swap characters

temp = str[first];

str[first] = str[last];

str[last] = temp;

// Move pointers towards each other

first++;

last--;

int main() {

char str[100] = "Hello Section B";

// Reversing str

reverse(str);
printf("%s\n", str);

return 0;}

Using Recursion
#include <stdio.h>

#include <string.h>

void reverse(char* str, int first, int last) {

// Base case is when first becomes greater than last

if (first >= last) {

return;

// Swap characters

char temp = str[first];

str[first] = str[last];

str[last] = temp;

// Recursively call the function with updated

// index pointers

reverse(str, first + 1, last - 1);

int main() {

char str[100] = "Hello World";

reverse(str, 0, strlen(str) - 1);

printf("%s", str);

return 0;
}

Using Library Function


#include <stdio.h>

#include <string.h>

int main() {

char str[] = "Hello World";

// Reversing string using strrev()

printf("Reversed String: %s", strrev(str));

return 0;

You might also like