C Introduction
Control Statement
Functions
Array
Pointers
Structure and Union
No Examples found for this topic - CodeHelpPro
Data Files
No Examples found for this topic - CodeHelpPro
Reverse a String by swapping
In this example, We will learn c program to reverse a string by swapping. For this, You must have knowledge in following topics
Algorithm
This is the algorithm of this program
Step 1: Start Step 2: Initialize string str, ch and interger n = 0 Step 3: Takes string from user and store to str variable Step 4: Repeat this step until str[i] != \\\'\\\\0\\\' Increase count by 1 Step 5: Assign i = 0 Step 6: Repeat this step until i < n / 2 ch = str[i] str[i] = str[n - i - 1] str[n - i - 1] = ch Step 8: Print str Step 9: End
Flowchart
This is the flowchart of this program

CODE: Reverse a String by swapping
Now, We will see the code to reverse a string.
#include <stdio.h>
#include <string.h>
int main(){
char str[1000], ch;
int n = 0;
printf("Enter string to reverse : ");
gets(str);
printf("\nOriginal String : %s", str);
//finding the length of the string
while (str[n] != '\0'){
n++;
}
for (int i = 0; i < n / 2; i++){
ch = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = ch;
}
printf("\nString After Reverse : %s", str);
return 0;
}
The output of above program is
Enter string to reverse : Suresh
String Before Reverse: Suresh
String After Reverse: hseruS
Subscribe
Login
0 Comments
Inline Feedbacks
View all comments