Answer to Question #248602 in C++ for Asim

Question #248602
Write a function called reversit() that reverses a C-string (an array of char). Use a for
loop that swaps the first and last characters, then the second and next-to-last characters,
and so on. The string should be passed to reversit() as an argument.
Write a program to exercise reversit(). The program should get a string from the user,
call reversit(), and print out the result. Use an input method that allows embedded
blanks. Test the program with Napoleon’s famous phrase, “Able was I ere I saw Elba.”
1
Expert's answer
2021-10-08T07:14:59-0400
#include <iostream>
#include <string.h>

#define SIZE 256

void reverse(char *str);

int main(int argc, char *argv[]) {
    char str[SIZE];

    std::cin.getline(str, SIZE);

    reverse(str);

    std::cout << str << std::endl;

    return 0;
}

void reverse(char *str) {
    size_t length = strlen(str) - 1;

    for (size_t i = 0; i < strlen(str) / 2; i++) {
        char temp = str[i];

        str[i] = str[length];

        str[length] = temp;

        length--;
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS