Getting Started With Arrays
Getting Started With Arrays
Definition
An array is a data structure that is used to store a list of objects all of the same type
Can have an array of numbers, of letters (a string), or even something more complicated like an
array of images, or sounds.
Note
Like regular variables, arrays have to be declared before they can be used
The dimension is the (maximum) number of elements that the array can hold
Syntax
Note
Elements
Accessing Elements
Use the index operator: [ ] to access individual elements of the array. The number inside the
square brackets is called the index.
Can treat each of these like single int variables and use them in assignment statements, etc.
Example
p[0] = 70;
1
Exercise
Create an array called x to store the following data: 65, 22, 10, 31, 47 by declaring the array and
writing an assignment statement for each element.
Shorthand
Note
int x[5];
x[5] = {65, 22, 10, 31, 47}; // Error! Only use = { } in declaration
For large arrays, you generate the data in a loop or else read the data in from a file
2
Important Note
And not: 1, 2, 3, 4, 5!
If you try to access an array element that is not there, your program will either crash, or at the very
least corrupt some of your other variables. This is a common programming mistake called: an
array out of bounds error.
Example
int p[5];
Exercise
Write a program where you create an array and then try to access elements that are out of bounds.
What happens when you run the program?
Printing Arrays
When it comes time to printing an int or float array to the screen, there is no control character
for that (though there is one for character arrays). Rather, you have to do a separate printf
statement for each component of the array.
The next topic of For loops will help us with this job!
3
Exercise
1. (a) Write a program to create an array with the elements as shown below. Write a series of printf
statements to print the contents of the array in the following form:
x[0]: 65
x[1]: 22
x[2]: 10
x[3]: 31
x[4]: 60
int m[20];
3. Suppose you have a sorted array x of dimension n (assume n is odd) and you want to compute
the median value, which is the number that comes in the middle of the sorted list. How would you
compute the median?
4
Definition
Example
str[0] = 'h';
str[1] = 'i';
str[2] = '\0';
Control Character
Example
Shorthand
Note
The compiler will put in the null terminating character for you
You can only use = in a string declaration you cannot use it after.
Example
5
strlen Function
Prototype: int strlen(char str[]) // Returns # characters in string (not including '\0')
Example
int n;
n = strlen(myStr); // n: 5
Example
Show memory table (in abbreviated form) for the following arrays. Assume starting address:
A000 B128
Arrays in Memory
Exercise
6
Visualizing Arrays
When working with arrays, it is important to realize that there are always two sets of numbers that
we’re typically dealing with:
It may help to develop following mental image or picture of the array. We will break it down into 2
cases: a numerical array and a character array.
Numerical Arrays
Suppose we’re working with this array: int x[5] = {20, 15, 40, 10, 76};
index: 0 1 2 3 4
data: 20 15 40 10 76 dim: 5
The indices are shown on top: 0, 1, 2, 3, 4. Note that there is always a mismatch between the
last index: 4 and the dimension of the array: 5. That is because in C, the first index is 0 and not 1.
In practice, when we are working with arrays in code, we do not deal with the data inside the array:
20, 15, 40, 10, 76 directly. Rather, we have to work symbolically with the variables that
represent the data. And so you need to have this picture in mind:
index: 0 1 2 3 4
7
Character Arrays
index: 0 1 2 3 4
dim: 5
data: h o m e '\0' strlen: 4
Here we have the same mismatch between the last index: 4 and the dimension of the array: 5. The
number 4 is also the number of letters in the string, which is called the string length (strlen). Note
that the index of the last letter here is 3, not 5 and not 4!
Again, when working with strings in code, we are often working in terms of loops and we have to deal
with the string symbolically, as shown below.
index: 0 1 2 3 4
dim: 5
data: str[0] str[1] str[2] str[3] '\0' strlen: 4
8
Exercise
int main
{
char c = "A";
int x[];
x[1] = 10;
x[5] = 20
2. Write a program which asks the user to enter 5 test scores. Store the values in an array, say
scores[].
3. A palindrome is a word that is spelled the same way forward and backward. Write a program
which asks the user to enter a 3-letter word and turn it into a palindrome by mirroring the letters.
Note: Use %s in the scanf to read in the string. This time, though, do not use a &. Just give the
string variable name; for example:
char myName[20];
scanf("%s", myName);
4. Set up a 4-dimensional integer array. (a) Write code to print a memory table of the array. (b)
Write the memory table by hand using starting address: A000 B000.
9
7. Write a letter guessing game program where the user has to guess a 3-letter word. Hard-
code the secret word at the start. The user gets 5 guesses to try to guess the word and at
each step, show them where they stand (game state).
Letter Guessing Game -------------------------------
I’m thinking of a 3-letter word. Try to guess it!
Hint: Set up variables as shown below. The ans variables store the letters of the secret word.
The state variables store the current state of the game, and what the user will see each round.
For these variables, please use the numbering starting at 0 instead of 1 (we will see why next
week). The in variable is the input from the user. Note: you will overwrite this variable for
each round. The variable enterKey is used to consume the \n (see last week’s notes about
scanf). The variable numCorrect keeps track of how many letter have been guessed thus far.
int main()
{
char answer[4] = 'cat'; //The secret word!
int numCorrect = 0;
// Round 1 ------------------------------
// etc
}
10