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
Write a program that prompts the user for 5 words, then prints them back to the terminal in reverse order. 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 dogs
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.
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.
You can verify your solution using this website. Be sure to check the “sample” option (not “population”).
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.02765