Homework 23 Solution

Write a program that reads a number n from the user, reads an n-word sentence from the user, and then prints out the sentence in reverse (but not the words). A typical run of the program might look like this:

Number of words: 3
Sentence: I am smart
smart am I

Use arrays not recursion! Turn In a printout of your program along with a screen capture showing it running on some clever sentence.

Solution

//KGS
// Hmwk 23
// This program reads an int N and a sentence with N words and prints it backwards.
// It uses arrays


#include <iostream>
#include <string>
using namespace
std;

int main() {
    int n;
    string* sent;

    cout << "Enter an integer: ";
    cin >> n;

    //Create the array
   
sent = new string[n];

    cout << "Enter a sentence containing " << n <<" words: ";

    //Fill the array
    for(int i=0;i<n;i++)
        cin >> sent[i];

    //Print the array from bottom to top
    for(i=n-1;i>=0;i--)
        cout << sent[i] << ' ';
    cout << endl;

    delete [] sent; // deallocate dynamic memory
    return 0;
}