fork download
  1. // Elaine Torrez CS1A
  2. // ____________________________________________________________
  3. //
  4. // DISPLAY STRING BACKWARD
  5. // ____________________________________________________________
  6. // This program prompts the user to enter a string and then
  7. // displays the string in reverse order.
  8. // ____________________________________________________________
  9. // INPUT
  10. // userStr : The string entered by the user
  11. //
  12. // OUTPUT
  13. // backward : The string displayed backward
  14. // ____________________________________________________________
  15.  
  16. #include <iostream>
  17. using namespace std;
  18.  
  19. // FUNCTION PROTOTYPE
  20. void displayBackward(const char *str);
  21.  
  22. int main()
  23. {
  24. /****************************************************
  25.   * VARIABLE DECLARATIONS
  26.   ****************************************************/
  27. const int SIZE = 100;
  28. char userStr[SIZE]; // INPUT string
  29.  
  30. /****************************************************
  31.   * INPUT
  32.   ****************************************************/
  33. cout << "Enter a string: ";
  34. cin.getline(userStr, SIZE);
  35.  
  36. /****************************************************
  37.   * OUTPUT
  38.   ****************************************************/
  39. cout << "\nString backward: ";
  40. displayBackward(userStr);
  41. cout << endl;
  42.  
  43. return 0;
  44. }
  45.  
  46. // *********************************************************
  47. // displayBackward
  48. // ---------------------------------------------------------
  49. // Displays all characters of a C-string in reverse order.
  50. // *********************************************************
  51. void displayBackward(const char *str)
  52. {
  53. int length = 0;
  54.  
  55. // Find the length of the string manually
  56. while (str[length] != '\0')
  57. length++;
  58.  
  59. // Print characters from back to front
  60. for (int i = length - 1; i >= 0; i--)
  61. cout << str[i];
  62. }
  63.  
Success #stdin #stdout 0.01s 5324KB
stdin
Gravity
stdout
Enter a string: 
String backward: ytivarG