Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that accepts a c-string input from the user and reverse the cont

ID: 3540265 • Letter: W

Question

Write a program that accepts a c-string input from the user and reverse the contents of the string. Your program should work by using 2 pointers. The "head" pointer should be set to the address of the first character in the string, and the "tail" pointer should be set to the address of the last character in the string (i.e., the character before the terminating null). The program should swap the characters referenced by these pointers, increment "head" to point to the next character, decrement "tail" to point to the second-to-last character and so on, until all characters have been swapped and the entire string reversed.


For example:

Hello there my friend

string reversed: dneirf ym ereht olleH

Explanation / Answer

#include<iostream>
#include<string>
using namespace std;
char *revrse( char * str1, char *head,char *tail);
int main(){

    string str;
    cout<<"enter the string ";
    getline(cin,str);
    int sze=str.size();
    char *str1=new char[sze+1];
    str1[sze]='';
    str.copy(str1,sze);
    char *head,*tail;
    head =str1;
    tail =str1+(sze-1);
    str1=revrse(str1,head,tail);
    cout<<str1;
    return 0;
}

char *revrse( char * str1, char *head,char *tail){
    char *head1=head;
    while(head<=tail){
        char temp=*head;
        *head=*tail;
        *tail=temp;
        head++;
        tail--;
    }
    return head1;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote