Tuesday, March 30, 2010

Introduction to Programming:Starting Out With Programming Logic and Design;Chapter 8:Arrays

Starting Out with Programming Logic and Design (2nd Edition)

1. Array Basics

Variables that we have learned about so far only allow for one piece of data at a time. If you were need to have many different pieces of data that would be an array. All of the pieces of data must be of the same data type. It is not possible in a running program to change an arrays size. In our psuedocode the declaration of an array is:

Declare Integer units [10]

Integer being replaced with data type, units with variable name and the number in the brackets with how many elements you will need in the array.

Array Elements and Subscripts

Storage locations in an array are called elements. To put information into an array, or to get it out, we would have to use a number to indicate which element of an array we want. That number is called a subscript. Because of the way computers work, the arrays are numbered starting with 0 and not 1. So the highest subscript in a 5 element array would be 4.

Assigning Values to Array Elements

To put a value into an array use the command to put a value into an array, we will psuedocode it as set, use the variable and put the value in it:

Set number[1]=80

Inputting and Outputting Array Contents

It is possible to read values from a keyboard and store them into an array as well as read them that way. You will need to use the input with the array name - subscript.

Using a Loop to Step Through an Array

In order to get all the information out of an array, a loop can be used. By using the variable from the loop to count up (or down), and using it as the subscript for the array name, we can get all the information out of it.

Processing the Elements of an Array

Processing array elements is no different than processing any other variable.

Array initialization

Most languages let you declare an array and then populate it at the same time by putting an = and the list of items separated by commas. This is known as an initialization list.

Array Bounds Checking

Most languages will error out if you try to put a value in an element that does not exist.

Watch for Off-by-One Errors

Because an array starts with 0 it is easy to ignore the fact that most people start counting with 1.  Watch for that simple mistake.

 

Programming Logic for Business



No comments:

Post a Comment