Arrays
Arrays are a fundamental data structure in programming that allow you to store multiple values of the same type under a single name. In C++, arrays are a fixed-size collection of elements that are stored in contiguous memory locations. Each element in an array can be accessed using an index, which is an integer value that represents the position of the element in the array. Check and understand the following example, then tackle the problems that follow.
Problem 1
Section titled “Problem 1”Write a program that prompts the user for 5 words, then prints them back to the terminal in reverse order. Note that “words” here implies strings separated by whitespace, so “hello,” counts as one word including the comma. Error handling is not required; the program may assume the user will enter exactly 5 words, one at a time. Use the stream extraction operator >> to read each word.
Your program must use a statically allocated (regular) C++ array in a meaningful way.
Enter a string: dogsEnter a string: chaseEnter a string: catsEnter a string: quicklyEnter a string: outside
In reverse: outside quickly cats chase dogsProblem 2
Section titled “Problem 2”Write a program that prompts the user for 10 numbers (represented as doubles) and calculates the sample standard deviation of those numbers.
The program must use a statically allocated C++ array in a meaningful way. You should use a constant for the number of elements (e.g., const int N = 10;) to make the code more readable and adaptable.
The sample standard deviation can be computed as:
where is the sample variance:
- is the -th number entered by the user
- is the mean of all numbers entered
- (the total number of numbers entered)
In other words:
- Compute the mean .
- Compute the squared difference between each number and .
- Compute the sum of the squared differences.
- Divide the sum by to get the variance .
- Take the square root of the variance to calculate the sample standard deviation .
- Print the result to the terminal.
Enter number #1: 1.0Enter number #2: 2.0Enter number #3: 3.0Enter number #4: 4.0Enter number #5: 5.0Enter number #6: 6.0Enter number #7: 7.0Enter number #8: 8.0Enter number #9: 9.0Enter number #10: 10.0
Standard deviation: 3.02765Here’s a small interactive simulator to test your program. Enter 10 numbers and the simulator will compute the sample standard deviation (uses N - 1 in the denominator).
Standard Deviation 📊
Enter values below and the simulator will compute the sample standard deviation (N - 1 in denominator).
Alternatively, you can verify your solution using this website. Be sure to check the “sample” option (not “population”).