In: Computer Science
solution using stack
Reversing a word or a sentence:
Write an algorithm that will display a given word in a reverse order.
- e.g. "Data Structures" will be "serutcurtS ataD".
1). ANSWER :
GIVENTHAT :
To Write an algorithm that will display a given word in a reverse order e.g. “Data Structures” will be “serutcurtS ataD”.
Algorithm to display the reverse string
1.Start.
2.Declare all the variables ( integer(i,j) and character (arrString
[100], temp) )
3.Enter the string to be reversed.
4.Find the length of string.
5.Initialize the variables i,j (i=0,j= stringlength-1)
6.Swap the position of array element using the loop((arrString [i]
is interchanged with (arrString[j]).
7.Increment i
8.Decrement j
9.If i < j then continue loop and goto step 6
10.Print the reversed string to user.
11.Stop.
Example C Program
#include<stdio.h>
#include<string.h>
int main()
{
// variable declarations
char arrString [100], temp;
int i, j = 0;
printf(" Enter the string to be reversed:");
gets(arrString ); // input string
//Initialize i,j
i = 0;
j = strlen(arrString ) - 1;
while (i < j)
{
//Swap characters
temp = arrString [i];
arrString [i] = arrString [j];
arrString [j] = temp;
i++;
j--;
}
printf("\nThe Reversed string is :%s", arrString ); // Output
return (0);
}
The above program Output :-