fork download
  1. //Maxwell Brewer CS1A Chapter 10, p. 588, #2
  2. //
  3. /*******************************************************************************
  4.  * REVERSE ARRAY CHARACTERS
  5.  * _____________________________________________________________________________
  6.  * This program accepts a string input from the user (up to a maximum number
  7.  * of characters). It then reverses the order of characters in the string
  8.  * and displays the reversed result.
  9.  *
  10.  * INPUT:
  11.  * str : A character array entered by the user (maximum 50 characters).
  12.  *
  13.  * OUTPUT:
  14.  * The reversed version of the entered string.
  15.  *
  16.  * EXAMPLE:
  17.  * Input: Hello, World!
  18.  * Output: !dlroW ,olleH
  19.  *******************************************************************************/
  20.  
  21. #include <iostream>
  22. #include <cstring> // For strlen function
  23. using namespace std;
  24.  
  25. // Function prototype
  26. void printReverse(char* str);
  27.  
  28. int main() {
  29. char str[50]; // String to be entered by user
  30.  
  31. // User prompt and input
  32. cout << "=============================================\n";
  33. cout << "Please enter some text\n";
  34. cout << "Note: with a max of 50 characters.\n";
  35. cout << "Your string: ";
  36.  
  37. cin.getline(str, 50); // Gets a complete line
  38.  
  39. cout << "=============================================\n\n";
  40.  
  41. // Print reverse string
  42. cout << "The reverse: ";
  43.  
  44. printReverse(str);
  45.  
  46. cout << "\n=============================================\n";
  47.  
  48. return 0;
  49. }
  50.  
  51. // Function definition
  52. void printReverse(char* str) {
  53.  
  54. // This function prints the string in reverse order.
  55. // We start from the last character and print until the first character.
  56.  
  57. // NOTE: We get the position of the last character using strlen, which gives
  58. // the number of characters in the string.
  59.  
  60. for (int i = strlen(str) - 1; i >= 0; i--) {
  61. // Print characters in reverse
  62. cout << str[i];
  63. }
  64. cout << endl; // End line for clean output
  65. }
Success #stdin #stdout 0.01s 5292KB
stdin
RACECAR
stdout
=============================================
Please enter some text
Note: with a max of 50 characters.
Your string: =============================================

The reverse: RACECAR

=============================================