/*! This file is auto-generated */ .wp-block-button__link{color:#fff;background-color:#32373c;border-radius:9999px;box-shadow:none;text-decoration:none;padding:calc(.667em + 2px) calc(1.333em + 2px);font-size:1.125em}.wp-block-file__button{background:#32373c;color:#fff;text-decoration:none} Problem 39 Write two versions of each strin... [FREE SOLUTION] | 91Ó°ÊÓ

91Ó°ÊÓ

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

Short Answer

Expert verified
Implement using both array subscripts and pointers, both compare character by character.

Step by step solution

01

Understanding Array Subscript Method

In the array subscript method, we use indexes to access each character of the strings. For example, if we have a string `str`, `str[i]` gives the character at the ith position of the string. We will use this approach first for each string comparison function.
02

Implementing strcmp Using Array Subscript

To compare two strings `s1` and `s2` using array subscripting, use a loop to iterate over the characters while they are equal. If a difference is found or the end of both strings is reached, return the difference between the current characters or zero if they are identical. ``` int strcmp_subscript(const char s1[], const char s2[]) { int i = 0; while (s1[i] && s1[i] == s2[i]) { i++; } return s1[i] - s2[i]; } ```
03

Understanding Pointer Arithmetic Method

In the pointer arithmetic method, you use pointers to iterate over the strings. You can directly compare the values that the pointers point to and move the pointer by incrementing it, i.e., `*pointer` gives the character value and `pointer++` moves to the next character.
04

Implementing strcmp Using Pointer Arithmetic

Implement the `strcmp` function using pointers. Initialize pointers to point at the start of each string, then increment them while characters are equal. Stop if a difference is found or both strings end, and return the character difference or zero. ``` int strcmp_pointer(const char *s1, const char *s2) { while (*s1 && *s1 == *s2) { s1++; s2++; } return *s1 - *s2; } ```
05

Compare and Conclude

Both methods achieve the same result, but the pointer method may be more efficient in certain compilers due to direct memory access. However, the array subscript method is often simpler and more readable for new programmers.

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 91Ó°ÊÓ!

Key Concepts

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

String Comparison
String comparison in C++ involves evaluating two strings to determine their relative ordering or equality. This operation is key in many applications, such as sorting or checking for unique values.
To compare strings, we often look at them as sequences of characters and compare each character pairwise. If we find any differences, we can conclude which string is greater or if they are equal. This is typically done using functions like `strcmp` in C++, which return zero if two strings are identical, a positive value if the first non-matching character in `s1` is greater, and a negative value if it's smaller.
In general, string comparison requires careful attention to character encoding and null-terminations to avoid errors. By understanding string comparison, we can manipulate and control data in programs more effectively.
Pointer Arithmetic
Pointer arithmetic is a technique in C++ that involves performing operations directly with memory addresses. It allows programmers to navigate through array-like data structures more efficiently. In pointer arithmetic, you work with the address rather than the index.
When using pointer arithmetic, incrementing a pointer (e.g., `pointer++`) moves it to the next block of memory of the data type it points to. This is valuable since it abstracts the index calculations and can lead to performance improvements in some cases.
By using pointers in string comparison, you directly access each character and can take advantage of lower-level operations. This technique can be a bit abstract for beginners but offers a powerful tool in optimizing code.
Array Subscripting
Array subscripting is a common method to access elements in a sequence using an index. In C++, you use the square brackets (e.g., `arr[i]`) to access the ith element of an array. This is a very intuitive and user-friendly approach, especially for beginners.
When comparing strings using array subscripting, you iterate over the characters using indices. With `str[i]`, you get direct access and can easily implement logic for comparison.
While subscripting is simple and readable, it abstracts away some of the details of memory access, potentially leading to less efficient code. Still, it is often the go-to approach because of its simplicity and ease of understanding.
Function Implementation
Function implementation in C++ involves writing the actual code for functions that define specific behavior in a program. When implementing a function like `strcmp`, you are responsible for deciding the logic flow and how it achieves its purpose.
For string comparison functions, your implementation might include loops, conditionals, and return statements to convey the logic of comparing two sequences of characters. You decide whether to use array subscripting or pointer arithmetic based on your optimization goals and readability.
Strong function implementation skills are crucial for writing efficient, clear, and maintainable code. Understanding the underlying concepts like pointer arithmetic or array subscripting enhances your ability to implement functions optimally in various contexts.

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

Perform the task specified by each of the following statements: a. Write the function header for function zero that takes a long integer array parameter bigIntegers and does not return a value. b. Write the function prototype for the function in part (a). c. Write the function header for function add1AndSum that takes an integer array parameter oneTooSmall and returns an integer. d. Write the function prototype for the function described in part (c)

(A Metric Conversion Program) Write a program that will assist the user with metric conversions. Your program should allow the user to specify the names of the units as strings (i.e., centimeters, liters, grams, etc., for the metric system and inches, quarts, pounds, etc., for the English system) and should respond to simple questions such as "How many inches are in 2 meters?" "How many liters are in 10 quarts?" Your program should recognize invalid conversions. For example, the question "How many feet are in 5 kilograms?" is not meaningful, because "feet" are units of length, while "kilograms" are units of weight

Write a program that inputs a line of text, tokenizes the line with function strtok and outputs the tokens in reverse order.

(Check Protection) Computers are frequently employed in check-writing systems such as payroll and accounts-payable applications. Many strange stories circulate regarding weekly paychecks being printed (by mistake) for amounts in excess of \(1 million. Weird amounts are printed by computerized check-writing systems, because of human error or machine failure. Systems designers build controls into their systems to prevent such erroneous checks from being issued. Another serious problem is the intentional alteration of a check amount by someone who intends to cash a check fraudulently. To prevent a dollar amount from being altered, most computerized check-writing systems employ a technique called check protection. Checks designed for imprinting by computer contain a fixed number of spaces in which the computer may print an amount. Suppose that a paycheck contains eight blank spaces in which the computer is supposed to print the amount of a weekly paycheck. If the amount is large, then all eight of those spaces will be filled, for example, 12345678 (position numbers) On the other hand, if the amount is less than \)1000, then several of the spaces would ordinarily be left blank. For example, 99.87 \-------- 12345678 contains three blank spaces. If a check is printed with blank spaces, it is easier for someone to alter the amount of the check. To prevent a check from being altered, many check-writing systems insert leading asterisks to protect the amount as follows: ***99.87 \-------- 12345678 Write a program that inputs a dollar amount to be printed on a check and then prints the amount in check-protected format with leading asterisks if necessary. Assume that nine spaces are available for printing an amount.

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.

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.