In: Computer Science
write a simple c program to reverse pairs of characters in a string. For exaple, "notified" becomes "edfitino". The reversal should be in this order in a simple easy to understand c program.
Hello the string reversal is done in 2 categories
1)when the string length is odd
-when it is odd,reversal is done from last index to 1st index and the 0th index is simply added to the last
2)when the string length is even
-when it is even the reversal is done in normal fashion itself
The input_string is the original string and ouput_string is the reversal string
//stdio is for standard input and output
#include <stdio.h>
//string is used for calculating length of the string
#include <string.h>
int main(int argc, char *argv[])
{
char
input_string[50]={'\0'},output_string[50]={'\0'};
int i,length_of_string=0,j=0,count=0;
//read the string
printf("Enter the String which you want to
reverse:");
scanf("%s",input_string);
//calculate the length of the string by using strlen()
function
length_of_string=strlen(input_string);
for(i=length_of_string-1;i>=0;i--)
{
//when string length is even
if(length_of_string%2==0)
{
//add last 2
charcters of the input to the first 2 characters and so on
if((i+2)%2==0)
{
output_string[j++]=input_string[i];
output_string[j++]=input_string[i+1];
}
else
{
continue;
}
}
//when string length is odd
else
{
//add first
character at the last index
if(i==0)
{
output_string[j]=input_string[i];
}
else
if((i+2)%2==0)
{
continue;
}
//add last 2
charcters of the input to the first 2 characters and so on
else
{
output_string[j++]=input_string[i];
output_string[j++]=input_string[i+1];
}
}
}
printf("%s",output_string);
return 0;
}
Thank you.....