Arrays
Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
To create an array, define the data type (like int) and specify the name of the array
followed by square brackets [ ].
Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
This statement accesses the value of the first element [0] in myNumbers:
Change an Array Element
To change the value of a specific element, refer to the index number:
Loop Through an Array
You can loop through the array elements with the for loop.
The following example outputs all elements in the myNumbers array:
Another common way to create arrays, is to specify the size of the array, and add
elements later:
Example
// Declare an array of four integers:
int myNumbers[4];
// Add elements
myNumbers[0] = 25;
myNumbers[1] = 50;
myNumbers[2] = 75;
myNumbers[3] = 100;
Why did the result show 20 instead of 5, when the array contains 5 elements?
- It is because the sizeof operator returns the size of a type in bytes.
You learned from the Data Types that an int type is usually 4 bytes, so from the
example above, 4 x 5 (4 bytes x 5 elements) = 20 bytes.
Knowing the memory size of an array is great when you are working with larger
programs that require good memory management.
String Functions
C also has many useful string functions, which can be used to perform certain
operations on strings.
To use them, you must include the <string.h> header file in your program:
#include <string.h>
String Length
For example, to get the length of a string, you can use the strlen() function:
Example
Concatenate Strings
To concatenate (combine) two strings, you can use the strcat() function:
Example
// Print str1
printf("%s", str1);
Compare Strings
To compare two strings, you can use the strcmp() function.
It returns 0 if the two strings are equal, otherwise a value that is not 0:
Example