This program must be written in c++, and full points go to the answer that works
ID: 643167 • Letter: T
Question
This program must be written in c++, and full points go to the answer that works and has the best explanation for each line of code.
Write a program that uses random number generation to create sentences. Use four arrays of pointers to char called article, noun, verb and preposition. Your program should create a sentence by selecting a word at random from each array in the following order: article, noun, verb, preposition, article and noun. Concatenate each word to the others previously chosen. Be sure to separate words by a space. Once the program is complete, use it to create a short paragraph (or a paper to hand in for some other course!)
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
int main( void )
{
// initialize 4 arrays of char pointers
char *article[] = { "the", "a", "one", "some", "any" };
char *noun[] = { "boy", "girl", "dog", "town", "car" };
char *verb[] = { "drove", "jumped", "ran", "walked", "skipped" };
char *preposition[] = { "to", "from", "over", "under", "on" };
char sentence[ 100 ] = ""; // completed sentence
size_t i; // loop counter
// create 20 sentences
for ( i = 1; i <= 20; ++i ) {
// randomly choose pieces of sentence
strcat( sentence, article[ rand() % 5 ] );
strcat( sentence, " " );
strcat( sentence, noun[ rand() % 5 ] );
strcat( sentence, " " );
strcat( sentence, verb[ rand() % 5 ] );
strcat( sentence, " " );
strcat( sentence, preposition[ rand() % 5 ] );
strcat( sentence, " " );
strcat( sentence, article[ rand() % 5 ] );
strcat( sentence, " " );
strcat( sentence, noun[ rand() % 5 ] );
// capitalize first letter and print sentence
putchar( toupper( sentence[ 0 ] ) );
printf( "%s. ", &sentence[ 1 ] );
sentence[ 0 ] = '';
} // end for
} // end main
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.