PDE - User Input Array Control (Lesson)
User Input Array Control
Using a Default Array
Here you will see an example of a default array used to build arrays of variable length depending on the desire of a user.
The default array here has been defaulted to all zeros. You could chose any number that you wanted for a default as long as the number was not going to be valid in your array? What would be wrong with the default being a value that could be in the array? In this case the size of the array will give away the numbers that do not belong. Other arrays may need to add or remove numbers depending on your purpose, and thus have a index position turned off for use. Having a number that would never be valid would allow code to check and know when to use the index position or not.
A. Examine the code below.
- What happens if the user picks 1 as their number, 5, 10, or 11 as currently written?
- What does TotalNbrs mean?
B. Below, we will load the random array with random numbers.
- What number range may be put in the array for each of these numbers chosen by the user? 1, 5, 10?
- By now I hope you know that using 11 would have blown up the program with an Out of Bounds Exception. Is an 11 out of bounds? Why?
C. Let's go through two additions in code to the code above to recount all of the items that we are using.
- Both additions will work and provide the same answer.
- Both can be simplified with the load of the random numbers above to save computer time, programmer time, and debugging time and only say the random number once, though allowing both objects to talk. One is closer to the final solution already. Which one would be the quickest to simplify and why?
- What does the boolean variable do? Does the boolean help create interest and provide a new dimension to the reading of numbers?
- In the count code, why is the long condition needed to get to the correct array length?
Addition 1: Using count to read the random array.
Addition 2: Using while to read the random array.
D. Below is the video of the code running. Note the input and outputs are shown.
1. What are the input(s) to the program?
2. What are the output(s) to the program?
Here is the video of the code.
Now that you have seen a default array in use, you may find many other uses for a generic array of a specific datatype to use for loading data.
Answers to these questions will be given to you later in the module.
IMAGES & VIDEO CREATED BY GAVS.