Array is another C/C++ data type. It is an aggregated same data type. Let start with a program example that doesn’t use loop to see array usefulness.
Create a project named myarray and add a source file named myarraysrc. Set your project to Compile as C Code. Build and run the following sample program and that follow.
| |
| |
|
|
score[4];
score[0],score[1],score[2],score[3]
int score[2] and score[2]
Searching An Array Element
|
|
A sample input and output.
|
In this example, the array score[ ] has 12 slots/index (0 – 11), which assigned values from user input until 0 is read in. Therefore the loop to read data into the array is different from the previous example. There we had a fixed number of elements to read. Here we stop reading data into the array when we read in a zero.
The program continues by asking the user what number he/she wants to look up. If the number is found, then it will print where the number was located. If the number isn’t found, it will notify the user. The method of doing this search is called a linear search, where the number is searched starting from the beginning of the array to the end of it. If the number doesn’t appear until the end of the array, this may take some time. With a lot of elements, this is not an efficient one. A more efficient method of searching is called a binary search introduced later in this worksheet.
Some examples of the array initialization are given below.
char myname[ ] = "Mike";
char yourname[5] = {'M','i','k','e','\0'};
int score[5] = {4, 2, 654, 0, 78};
Individual elements can be specified using braces and commas, as with score[5] and yourname[5]. Two strings,yourname and myname are initialized to the same value. When initializing arrays as above, one can omit the array size given in the brackets, as in myname[ ] (unsized array). This is because the size of the array can be determined by the number of initial values. Also remember that a string such as “Mike” actually contains five characters because the null character is used to terminate a string and this is specific to string only.
Arrays allow programmers to group related items of the same data type in one variable. However, when referring to an array, one has to specify not only the array or variable name but also the index number of interest. Let us first look at strings that are special types of arrays, since we are more familiar with them. Build and run the following program then try answering the questions that follow.
#include<stdio.h>
void main() { char a[11] = "Boring"; printf("Index 0 has %c\n", a[0]); printf("Index 1 has %c\n", a[1]); printf("Index 2 has %c\n", a[2]); printf("Index 3 has %c\n", a[3]); printf("Index 4 has %c\n", a[4]); printf("Index 5 has %c\n", a[5]); printf("Index 6 has %c\n", a[6]); printf("Index 7 has %c\n", a[7]); printf("Numerically, the a[6] is %d\n", a[6]); }
|
|
|
|
|
|
| |
|
|
|
|
|
|
|
When the first printf() uncommented the following is the output.
|