Warning: foreach() argument must be of type array|object, bool given in /var/www/html/web/app/themes/studypress-core-theme/template-parts/header/mobile-offcanvas.php on line 20

Write a program that uses function strncmp to compare two strings input by the user. The program should input the number of characters to compare. The program should state whether the first string is less than, equal to or greater than the second string. Write a program that uses random number generation to create sentences. The program should use four arrays of pointers to char called article, noun, verb and preposition. The 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. As each word is picked, it should be concatenated to the previous words in an array that is large enough to hold the entire sentence. The words should be separated by spaces. When the final sentence is output, it should start with a capital letter and end with a period. The program should generate 20 such sentences.

Short Answer

Expert verified
The program compares strings with `strncmp` and generates random sentences using word arrays.

Step by step solution

01

Understanding the Problem

The task is twofold: 1) Write a program using `strncmp` to compare two strings based on user input, determining if the first string is less than, equal to, or greater than the second. 2) Write a program using arrays to create 20 sentences by concatenating random words.
02

Plan the First Part

To compare two strings with `strncmp`, get user input for two strings and the number of characters `n` to compare. Use `strncmp` to compare these `n` characters and print the result indicating if the first string is less than, equal to, or greater than the second.
03

Implement the First Part

1. Include necessary libraries like `iostream` and `cstring`. 2. Use `std::cin` to get the two strings and the comparison length `n` from the user. 3. Use `strncmp()` to compare the first `n` characters of the strings. 4. Output whether the first string is less than, equal to, or greater than the second based on the result of `strncmp()`.
04

Plan the Second Part

Define arrays of strings: `article`, `noun`, `verb`, and `preposition`. Each holds words of its respective type. Randomly pick words from these arrays and form a grammatically structured sentence. Repeat this 20 times.
05

Implement the Second Part

1. Include necessary libraries like `iostream`, `cstdlib`, and `ctime`. 2. Define arrays for `article`, `noun`, `verb`, and `preposition`. 3. Initialize sentences using a loop to concatenate randomly chosen words from each array using `rand()` function. 4. Capitalize the first letter and ensure the sentence ends with a period. 5. Repeat to produce 20 sentences.
06

Testing and Output

Run both parts of the program. For the first, input different strings and lengths. For the second, observe the sentences for grammatical structure, starting capitalization, and ending punctuation.

Unlock Step-by-Step Solutions & Ace Your Exams!

  • Full Textbook Solutions

    Get detailed explanations and key concepts

  • Unlimited Al creation

    Al flashcards, explanations, exams and more...

  • Ads-free access

    To over 500 millions flashcards

  • Money-back guarantee

    We refund you if you fail your exam.

Over 30 million students worldwide already upgrade their learning with Vaia!

Key Concepts

These are the key concepts you need to understand to accurately answer the question.

String Comparison
String comparison in C++ is a fundamental concept that involves determining the relative order of two strings based on their content. In this context, the `strncmp` function is particularly useful because it allows you to compare a specific number of characters from each string, providing more fine-grained control over the comparison.

**How Does `strncmp` Work?**
The function `strncmp` is part of the C++ Standard Library in ``. It compares up to `n` characters of two strings. The comparison is done lexicographically:
  • If the function returns a value less than zero, the first string is considered less than the second.
  • A value of zero indicates the strings are equal.
  • A value greater than zero shows the first string is greater.
**Practical Usage**
In practical scenarios, using `strncmp` can be particularly advantageous when working with only a portion of strings, such as prefixes. This is especially useful in applications like sorting, searching, and validating inputs. It’s key in ensuring accurate and efficient handling of string data based on partial information.
Knowing Data Types
Data types are the building blocks of programming in C++. They define the type of data a variable can hold and what operations can be performed on them. In C++, understanding and using the correct data types is crucial for developing efficient and error-free programs.

**Common Data Types in C++**
  • int: For integer numbers.
  • float and double: For floating-point numbers, with `double` offering higher precision.
  • char: For single characters.
  • string: Represented in C++ by the `` library for text data.
Data types like `arrays` and `pointers` are also essential, allowing you to store multiple values and manage dynamic memory, respectively.

**Why Data Types Matter**
Selecting the right data type affects the memory usage, performance, and reliability of the program. For example, using `int` for values that never exceed its limits ensures efficient memory usage. Recognizing and applying the correct data type is fundamental to successful C++ programming.
Random Sentence Generation
Random sentence generation is an interesting exercise that combines randomness with basic string handling. In the provided task, it involves forming grammatical sentences by selecting random words from predefined categories such as articles, nouns, verbs, and prepositions.

**Components of a Random Sentence Generation**
Using arrays of strings, each array holds words of a specific type.
  • article: Words like "the," "a," and "an."
  • noun: Words like "cat," "dog," or "car."
  • verb: Actions like "runs," "jumps," or "drives."
  • preposition: Words like "over," "under," or "by."
By selecting one word from each category and joining them, you form a complete sentence. To add variety, you can use the `rand()` function, which generates pseudo-random numbers to randomly pick words from each array.

**Implementing Randomness**
Ensure randomness by seeding the random number generator with the current time. This is done using `srand(time(0))`, which sets the seed based on the current clock. Proper implementation should include starting the sentence with a capital letter and ending with a period.
Using Arrays in C++
Arrays in C++ are an essential data structure used to store a collection of items of the same type. They provide a simple and straightforward way to keep track of data sets such as lists of numbers or words.

**Defining Arrays**
Arrays are defined by specifying the type of elements and the number of elements the array can hold. For example, `int numbers[10];` creates an array of 10 integers.
  • Arrays are zero-indexed, meaning the first element is accessed with index 0.
  • They can be single-dimensional or multi-dimensional, like matrices.
**Why Use Arrays?**
The main advantage of arrays is that they allow you to use a single name to represent a collection of data, facilitating easy access and manipulation of data elements using loops.

**Array of Pointers**
In tasks like random sentence generation, arrays of pointers to `char` are useful. These allow dynamic manipulation and memory-efficient string handling, as they're not sized by the length of each string but rather hold references. This is crucial for large-scale applications and efficient use of resources.

One App. One Place for Learning.

All the tools & learning materials you need for study success - in one app.

Get started for free

Most popular questions from this chapter

For each of the following, write C++ statements that perform the specified task. Assume that double-precision, floating-point numbers are stored in eight bytes and that the starting address of the array is at location 1002500 in memory. Each part of the exercise should use the results of previous parts where appropriate. a. Declare an array of type double called numbers with 10 elements, and initialize the elements to the values 0.0, 1.1, 2.2, ..., 9.9. Assume that the symbolic constant SIZE has been defined as 10. b. Declare a pointer nPtr that points to a variable of type double. c. Use a for statement to print the elements of array numbers using array subscript notation. Print each number with one position of precision to the right of the decimal point. d. Write two separate statements that each assign the starting address of array numbers to the pointer variable nPtr. e. Use a for statement to print the elements of array numbers using pointer/offset notation with pointer nPtr. f. Use a for statement to print the elements of array numbers using pointer/offset notation with the array name as the pointer. g. Use a for statement to print the elements of array numbers using pointer/subscript notation with pointer nPtr. h. Refer to the fourth element of array numbers using array subscript notation, pointer/offset notation with the array name as the pointer, pointer subscript notation with nPtr and pointer/offset notation with nPtr. i. Assuming that nPtr points to the beginning of array numbers, what address is referenced by nPtr + 8? What value is stored at that location? j. Assuming that nPtr points to numbers[ 5 ], what address is referenced by nPtr after nPtr -= 4 is executed? What is the value stored at that location?

Write two versions of each string copy and string-concatenation function in Fig. 8.30. The first version should use array subscripting, and the second should use pointers and pointer arithmetic.

(Text Analysis) The availability of computers with string-manipulation capabilities has resulted in some rather interesting approaches to analyzing the writings of great authors. Much attention has been focused on whether William Shakespeare ever lived. Some scholars believe there is substantial evidence indicating that Christopher Marlowe or other authors actually penned the masterpieces attributed to Shakespeare. Researchers have used computers to find similarities in the writings of these two authors. This exercise examines three methods for analyzing texts with a computer. Note that thousands of texts, including Shakespeare, are available online at www.gutenberg.org. a. Write a program that reads several lines of text from the keyboard and prints a table indicating the number of occurrences of each letter of the alphabet in the text. For example, the phrase To be, or not to be: that is the question: contains one "a," two "b's," no "c's," etc. b. Write a program that reads several lines of text and prints a table indicating the number of one-letter words, two-letter words, threeletter words, etc., appearing in the text. For example, the phrase Whether 'tis nobler in the mind to suffer contains the following word lengths and occurrences:c. Write a program that reads several lines of text and prints a table indicating the number of occurrences of each different word in the text. The first version of your program should include the words in the table in the same order in which they appear in the text. For example, the lines To be, or not to be: that is the question: Whether 'tis nobler in the mind to suffer contain the words "to" three times, the word "be" two times, the word "or" once, etc. A more interesting (and useful) printout should then be attempted in which the words are sorted alphabetically.

(Printing Dates in Various Formats) Dates are commonly printed in several different formats in business correspondence. Two of the more common formats are 07/21/1955 July 21, 1955 Write a program that reads a date in the first format and prints that date in the second format

For each of the following, write a single statement that performs the specified task. Assume that long integer variables value1 and value2 have been declared and value1 has been initialized to 200000. a. Declare the variable longPtr to be a pointer to an object of type long. b. Assign the address of variable value1 to pointer variable longPtr. c. Print the value of the object pointed to by longPtr. d. Assign the value of the object pointed to by longPtr to variable value2. e. Print the value of value2. f. Print the address of value1. g. Print the address stored in longPtr. Is the value printed the same as value1's address

See all solutions

Recommended explanations on Computer Science Textbooks

View all explanations

What do you think about this solution?

We value your feedback to improve our textbook solutions.

Study anywhere. Anytime. Across all devices.

Sign-up for free