Skip to content

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.

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.

Example Output
Enter a string: dogs
Enter a string: chase
Enter a string: cats
Enter a string: quickly
Enter a string: outside
In reverse: outside quickly cats chase dogs

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 SS can be computed as:

S=VS = \sqrt{V}

where VV is the sample variance:

V=i=1N(xixˉ)2N1V = \frac{\sum_{i=1}^{N}(x_i - \bar{x})^2}{N - 1}
  • xix_i is the ii-th number entered by the user
  • xˉ\bar{x} is the mean of all numbers entered
  • N=10N = 10 (the total number of numbers entered)

In other words:

  1. Compute the mean xˉ\bar{x}.
  2. Compute the squared difference between each number and xˉ\bar{x}.
  3. Compute the sum of the squared differences.
  4. Divide the sum by N1=9N - 1 = 9 to get the variance VV.
  5. Take the square root of the variance to calculate the sample standard deviation SS.
  6. Print the result to the terminal.
Example Output
Enter number #1: 1.0
Enter number #2: 2.0
Enter number #3: 3.0
Enter number #4: 4.0
Enter number #5: 5.0
Enter number #6: 6.0
Enter number #7: 7.0
Enter number #8: 8.0
Enter number #9: 9.0
Enter number #10: 10.0
Standard deviation: 3.02765

Here’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).

Mean 5.50000
Standard Deviation 3.02765

Alternatively, you can verify your solution using this website. Be sure to check the “sample” option (not “population”).