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. // Function prototype
  25. void displayBackward(const char *str, int length);
  26.  
  27. int main()
  28. {
  29. // DATA DICTIONARY
  30. // SIZE - size of the character array (constant)
  31. // userString - the C-string entered by the user
  32. // length - number of characters in the string
  33. const int SIZE = 100;
  34. char userString[SIZE];
  35. int length;
  36.  
  37. // Get the string from the user
  38. cout << "Enter a string: ";
  39. cin.getline(userString, SIZE);
  40. length = strlen(userString);
  41.  
  42. // Display the string backward
  43. cout << "Backward: ";
  44. displayBackward(userString, length);
  45. cout << endl;
  46.  
  47. return 0;
  48. }
  49.  
  50. // Displays a C-string backward. The length parameter is used as the
  51. // counter, starting at the end of the string and counting down to the
  52. // first character.
  53. void displayBackward(const char *str, int length)
  54. {
  55. while (length > 0)
  56. {
  57. length--;
  58. cout << *(str + length);
  59. }
  60. }
Success #stdin #stdout 0s 544KB
stdin
apples
stdout
Enter a string: Backward: selppa