C Programming

Page 55

DECLARING ARRAYS Arrays may consist of any of the valid data types. Arrays are declared along with all other variables in the declaration section of the program. /* Introducing array's #include <stdio.h>

*/

main() { int numbers[100]; float averages[20]; numbers[2] = 10; --numbers[2]; printf("The 3rd element of array numbers is %d\n", numbers[2]); }

The above program declares two arrays, assigns 10 to the value of the 3rd element of array numbers, decrements this value ( --numbers[2] ), and finally prints the value. The number of elements that each array is to have is included inside the square brackets.

ASSIGNING INITIAL VALUES TO ARRAYS The declaration is preceded by the word static. The initial values are enclosed in braces, eg, #include <stdio.h> main() { int x; static int values[] = { 1,2,3,4,5,6,7,8,9 }; static char word[] = { 'H','e','l','l','o' }; for( x = 0; x < 9; ++x ) printf("Values [%d] is %d\n", x, values[x]); }

The previous program declares two arrays, values and word. Note that inside the squarebrackets there is no variable to indicate how big the array is to be. In this case, C initializes the array to the number of elements that appear within the initialize braces. So values consist of 9 elements (numbered 0 to 8) and the char array word has 5 elements. The following program shows how to initialise all the elements of an integer based array to the value 10, using a for loop to cycle through each element in turn. #include <stdio.h> main() { int count; int values[100]; for( count = 0; count < 100; count++ )

55


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.