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.

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.

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

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 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.

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

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