Computer Science, asked by anindyaadhikari13, 3 months ago

Language: C and C++
Task: Take a string as input and display the reverse of it.
Sample Input: ABC
Sample Output: CBA

Answers

Answered by MrTSR
4

Answer

  • C program to get reverse of Words in given string

#include<stdio.h>

#include<string.h>

int GetReverseWords(char *str,char *str1,int c);

main()

{

int i,j=0,len,k,c=0;

char str1[100],str2[10][100];

printf("Enter a sentence to get reverse of each word\n");

gets(str1);

len=strlen(str1);

k=0;

for(i=0;i<len;i++)

{

if(str1[i]!=' ')

{

 str2[k][j]=str1[i];

 j++;

}

else

{

 str2[k][j]='\0';

 j=0;

 k++;

}

}

str2[k][j]='\0';

for(i=0;i<=k;i++)

{

  c=GetReverseWords(str2[i],str1,c);

str1[c]=' ';

c++;

}

str1[c]='\0';

printf("%s\n",str1);

}

int GetReverseWords(char *str,char *str1,int c)

{

int j;

 for(j=strlen(str)-1;j>=0;j--)

        {

         str1[c]=str[j];

         c++;

        }

        return c;

}

EXAMPLE:

Enter a sentence to get reverse of each word  

ABC

OUTPUT

CBA

  • C++ PROGRAM TO GET REVERSE OF A STRING

#include <iostream>

using namespace std;

void reverse(const string& a);

int main() {

 string str;

 cout << " Enter a string " << endl;

 getline(cin, str);

 reverse(str);

 return 0;    

}

void reverse(const string& str) {

 size_t numOfChars = str.size();

 if(numOfChars == 1) {

   cout << str << endl;

 }

 else {

   cout << str[numOfChars - 1];

   reverse(str.substr(0, numOfChars - 1));

 }

}

OUTPUT

Enter a string

ABC

CBA

Answered by Oreki
4

\text{\large\bf C}

   \texttt{int main() \{}\\\texttt{\hspace{1em} char str[50];}\\\texttt{\hspace{1em} printf("String : ");}\\\texttt{\hspace{1em} gets(str);}\\\\\texttt{\hspace{1em} // Reversing the string}\\\texttt{\hspace{1em}  strrev(str);}\\\texttt{\hspace{1em}  printf("Reverse - \%s", str);}\\\texttt{\hspace{1em}  return 0;}\\\texttt{\}}

\text{\large\bf C}++

   \texttt{\#includ\symbol{101} "iostream"}\\\\\texttt{using n\symbol{97}mespace std;}\\\\\texttt{int main() \{}\\\texttt{\hspace{1em} string text;}\\\texttt{\hspace{1em} cout &lt;&lt; "Enter a string : ";}\\\texttt{\hspace{1em} cin &gt;&gt; text;}\\\\\texttt{\hspace{1em} cout &lt;&lt; "Reversed string - "}\\\texttt{\hspace{8em}   + string(text.rbegin(), text.rend()) &lt;&lt; endl;}\\\texttt{\hspace{1em}  return 0;}\\\texttt{\}}

Similar questions