C PROGRAMMING QUESTION This program works it is supposed to
C PROGRAMMING QUESTION! This program works, (it is supposed to return a reversed string) but my assignment is to have the string print in main() how can I edit the code to do this? Thank you!
#include <stdio.h>
#define STRINGLENGTH 100
void reverse(char*);
int main()
{
char words[STRINGLENGTH];
char *p;
p = words;
printf(\"I reverse strings! Enter a string:\ \");
fgets(words, 100, stdin);
printf(\"The reversed string is:\ \");
reverse(p);
return 0;
}
void reverse(char *p)
{
char x;
int end = strlen(p)-1;
for (x = end; x >= 0; --x)
{
printf(\"%c\", p[x]);
}
}
Solution
#include<stdio.h>
#include<string.h>
#define STRINGLENGTH 100
void reverse(char*);
int main()
{
char words[STRINGLENGTH];
printf(\"\ I reverse strings! Enter a string:\ \");
fgets(words, 100, stdin);
words[strlen(words)-1]=\'\\0\'; /*As fgets append a newline implicitlly at the end of string,
I have just replaced it by null charecter \'\\0\' */
reverse(words);
printf(\"\ The reversed string - %s\ \",words);
return 0;
}
void reverse(char *p)
{
int l=strlen(p),i,m=l/2;
char temp;
l--;
for(i=0;i<m;i++)
{
temp=p[i];
p[i]=p[l];
p[l]=temp;
l--;
}
}
Here reverse(char *p) function reverses the whole string p and logic behind this
function is as follows -
initially l contains the size of string p, as starting index of an array is 0 (zero)
so that the last charecter is in the index (l-1) and for this reason I have decremented the value
of l before for loop.
Value of m indicates the middle of the string p.
In the for loop i initialized with value 0 that the starting index of the string
and l points to the last index of the string.
In each iteration of the for loop I have interchanged the charecter at index i with the charecter
at index l and vice-versa.
At the end of the loop l is decremented by 1 and i incremented by 1 and this for repeates until we
have not reached the middle of string that is (m-1) as index starts from 0 instead of 1.
At the end of this for loop the whole string is reversed.
Change your reverse function with this reverse function.

