0% found this document useful (0 votes)
16 views

Getting Started With Arrays

How to work with arrays mathematically

Uploaded by

c.p.b.4295
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Getting Started With Arrays

How to work with arrays mathematically

Uploaded by

c.p.b.4295
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

ECE 270 Computer Methods in ECE

Getting Started With Arrays


Winter 2023 Instructor: Paul Watta

Goal from the Start

Process lots of numbers

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

But need to specify 2 things now: type and dimension

The dimension is the (maximum) number of elements that the array can hold

Syntax

int p[5]; // Declaration statement for an array

Note

This allocates space for 5 integers

Elements

The individual numbers in an array are called elements

Accessing Elements

Use the index operator: [ ] to access individual elements of the array. The number inside the
square brackets is called the index.

p[0], p[1], p[2], ...

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

int x[5] = {65, 22, 10, 31, 47};

Note

Only works during declaration, not afterwards! So this won’t work:

int x[5];

x[5] = {65, 22, 10, 31, 47}; // Error! Only use = { } in declaration

This shortcut is used only for relatively small arrays

For large arrays, you generate the data in a loop or else read the data in from a file

2
Important Note

In C, the first index is 0 and not 1!

So for a 5-element array, the valid indices are: 0, 1, 2, 3, 4

And not: 1, 2, 3, 4, 5!

Array Out of Bounds Error

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];

p[-1] = 100; //Array out of bounds error! There is no index -1

p[5] = 100; //Array out of bounds error! There is no index 5

p[20] = 100; //Array out of bounds error! There is not index 20

p[1.5] = 100; //Array index error! Array indices must be integers.

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

(b) Compute the average value of the above array

2. Given the following declaration:

int m[20];

(a) What are the valid indices for the array?


(b) What is the first index?
(c) What is the last?
(d) What happens when you try to access: 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

A string is a sequence of characters. In C, a string is stored as a char array

The array is terminated with the null character: '\0'

Example

Store the word: "hi" in C

char str[3]; //We need one extra space for the \0

str[0] = 'h';
str[1] = 'i';
str[2] = '\0';

Control Character

Use %s in a printf to print an entire string

Example

printf("\nstr: %s", str);

Shorthand

char str[3] = "hi";

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

char str[3] = "hi";

str = "go"; // ERROR! Cannot use = after declaration

5
strlen Function

Prototype: int strlen(char str[]) // Returns # characters in string (not including '\0')

Example

int n;

char myStr[6] = "apple";

n = strlen(myStr); // n: 5

Example

Show memory table (in abbreviated form) for the following arrays. Assume starting address:
A000 B128

char str[] = "CAB"


int x[] = {10, 20, 30, 40};

Arrays in Memory

Address (HEX) Contents (Dec) Variables

Exercise

Write a program to generate these arrays and the memory table.

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:

1. The values stored in the array

2. The index of where those values are in the array

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

data: x[0] x[1] x[2] x[3] x[4] dim: 5

7
Character Arrays

Suppose we’re working with this string: char str[5] = "home";

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

1. Debug the following code:

int main
{
char c = "A";

char str[3] = 'ABC';

int x[];

x[1] = 10;

x[5] = 20

printf("\nstr: %d", str[]);

printf("\nx: %d", x);

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.

Please enter a 3-letter string: pul

6-letter palindrome: pullup

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];

printf("\nPlease enter your first name: ");

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.

5. Repeat #4 but work with a character array (string).

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!

Mystery Word: --- Points: 0


Guess: a

Mystery Word: -a- Points: 1


Guess: m

Mystery Word: -a- Points: 1


Guess: c

Mystery Word: ca- Points: 2


Guess: t

Mystery Word: cat Points: 3

You got it! I was thinking of the word cat!

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!

char state = {'-', '-', '-'}; // Current state of the game

char in; // The input (letter) from the user


char enterKey; // Used to consume the \n in scanf

int numCorrect = 0;

// Round 1 ------------------------------
// etc
}

10

You might also like