fork download
  1. //Ryan Shahriyarpour CS1A Chapter 10 Question 2
  2. /*****************************************************************************
  3.  *
  4.  * Backward String
  5.  *
  6.  *********************
  7.  *
  8.  * This program asks the user to enter a string, then passes a pointer to
  9.  * that C-string to a function that displays the contents backward.
  10.  * For example, "Gravity" is displayed as "ytivarG".
  11.  *
  12.  * INPUT
  13.  * userString - a line of text entered by the user
  14.  *
  15.  * OUTPUT
  16.  * The same text displayed in reverse order
  17.  *
  18.  ****************************************************************************/
  19.  
  20. #include <iostream>
  21. #include <cstring>
  22. using namespace std;
  23.  
  24. // Constant for the size of the character array
  25. const int SIZE = 100;
  26.  
  27. // Function prototype
  28. void displayBackward(const char *str);
  29.  
  30. int main()
  31. {
  32. // DATA DICTIONARY
  33. // SIZE - size of the character array (constant)
  34. // userString - the C-string entered by the user
  35. char userString[SIZE];
  36.  
  37. // Get the string from the user
  38. cout << "Enter a string: ";
  39. cin.getline(userString, SIZE);
  40.  
  41. // Display the string backward
  42. cout << "Backward: ";
  43. displayBackward(userString);
  44. cout << endl;
  45.  
  46. return 0;
  47. }
  48.  
  49. // Displays the contents of a C-string backward.
  50. // Starts at the last character and walks back to the first.
  51. void displayBackward(const char *str)
  52. {
  53. // DATA DICTIONARY
  54. // index - position of the character being displayed
  55. int index;
  56.  
  57. for (index = strlen(str) - 1; index >= 0; index--)
  58. cout << *(str + index);
  59. }
Success #stdin #stdout 0s 544KB
stdin
apples
stdout
Enter a string: Backward: selppa