You are on page 1of 2

Arrays are of two types single dimension array and multi-dimension array.

Each of these array type can be of either static array or dynamic array. Static array s have their sizes declared from the start and the size cannot be changed after declaration. Dynamic arrays that allow you to dynamically change their size at r untime, but they require more advanced techniques such as pointers and memory al location. It helps to visualize an array as a spreadsheet. A single dimension array is rep resented be a single column, whereas a multiple dimensional array would span out n columns by n rows. In this tutorial, you will learn how to declare, initiali ze and access single and multi dimensional arrays. Single Dimension Arrays Declaring Single Dimension Arrays Arrays can be declared using any of the data types available in C. Array size mu st be declared using constant value before initialization. A single dimensional array will be useful for simple grouping of data that is relatively small in si ze. You can declare a single dimensional array as follows: Sample Code <data type> array_name[size_of_array]; Copyright exforsys.com Say we want to store a group of 3 possible data information that correspond to a char value, we can declare it like this: Sample Code char game_map[4]; Copyright exforsys.com Note: In C language the end of string is marked by the null character ' '. Hence to store a group of 3 possible string data. We declare the array as char game_m ap[4]; This applies for char type array. One-dimensional string array containing 3 elements. Array Element game_map[0] game_map[1] game_map[2] Data S R D One-dimensional integer array containing 3 elements. Sample Code int emp_code[3]; Copyright exforsys.com Array Element emp_code[0] emp_code[1] Data 7 5 8 Initializing Single Dimension Arrays emp_code[2] game_map[3]

Array can be initialized in two ways, initializing on declaration or initialized by assignment. Initializing on Declaration

If you know the values you want in the array at declaration time, you can initia lize an array as follows: Syntax: Sample Code <data type> array_name[size_of_array] = {element 1, element 2, ...}; Copyright exforsys.com Example: Sample Code char game_map[3] = {'S', 'R', 'D'}; Copyright exforsys.com This line of code creates an array of 3 chars containing the values 'S', 'R ', a nd 'D'. Initialized by Assignment Sample Code char game_map[3]; game_map[0] = 'S'; game_map[1] = 'R'; game_map[2] = 'D'; Copyright exforsys.com Accessing Single Dimension Array Elements Arrays are 0-indexed, so the first array element is at index = 0, and the highes t is size_of_array 1. To access an array element at a given index you would use th e following syntax: Sample Code array_name[index_of_element]; Copyright exforsys.com

You might also like