Q11. Write a code to reverse a string

Given a string and the task is to write a algorithm and program to reverse a string. A string is sequence of characters terminated with a null character \0. So we are given a input string and we need to print its reverse order.
For Example: We have given input string as “ALFATECHLAB” and it’s reverse output we have to find out.
Input=”ALFATECHLAB”
Output=”BALHCETAFLA”

Explanation:
1. First declare a string variable and initialize an empty string to “ALFATECHLAB”.

2. Now we have to calculate the length of the string which we can do using loop(increment the value of count until the string is \0) or using the in-build function(strlen function).

3. Define two variables start = 0 and end = length -1.(Suppose “ALFATECHLAB” has a length of 11, then we will swap the 0th character with the 10th character, the 1st character with the 9th character, and the loop will iterate until length / 2 = 5).

4. Iterate the loop from i = 0 to i = length / 2 and increment the variable i by 1.

5. As we already define the start and end variable values, so now we just have to swap the characters one by one and increment the value of start += 1 and decrement the value of end- = 1 during each iteration.

6. After completing iteration print the string and output will be “BALHCETAFLA”.

Algorithm For Reverse A String

//Algorithm To Reverse A String
START
Step 1 -> Input string str1.
Step 2 -> calculate the length of the string.
Step 3 -> define start=0 and end=length-1;
Step 4 -> for i=0 to length/2.
temp=str1[start];
str1[start]=str1[end];
str1[end]=temp;
start+=1;
end-=1;
Loop End
step 5-> Display String str1.
STOP

Code For Reverse A String

Output

orip ni gnidoc

Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number