C Programming 7
C Programming 7
Lecture Seven
C - Arrays
int num[100];
float temp[20];
char ch[50];
num is an array of type int, which can only store 100 elements of
type int.
temp is an array of type float, which can only store 20 elements
of type float.
ch is an array of type char, which can only store 50 elements of
type char.
Initializing Array
When an array is declared inside a function the
elements of the array have garbage value. If an array is
global or static, then its elements are automatically
initialized to 0. We can explicitly initialize elements of
an array at the time of declaration using the following
syntax:
Syntax:
datatype array_name[size] = { val1, val2, val3, ..... valN };
Cont….
datatype is the type of elements of an array.
array_name is the variable name, which must be any
valid identifier.
size is the size of the array.
val1, val2 … are the constants known as initializers.
Each value is separated by a comma(,) and then there
is a semi-colon (;) after the closing curly brace (}).
Cont….
The simplest way to initialize an array is by using the index
of each element. We can initialize each element of the array
by using the index. Consider the following example.
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
Here is are some examples
int arr[9] = {11, 22, 33, 44, 55, 66, 77, 88, 99}; // an array of 9 ints
While initializing 1-D array it is optional to specify the size of
the array, so you can also write the above statements as:
float temp[] = {12.3, 4.1, 3.8, 9.5, 4.5}; // an array of 5 floats
int arr[] = {11, 22, 33, 44, 55, 66, 77, 88, 99}; // an array of 9 ints
If the number of initializers is less than the specified size then
the remaining elements of the array are assigned a value of 0
float temp[5] = {12.3, 4.1};
Cont…
here the size of temp array is 5 but there are only two
initializers. After this initialization the elements of the
array are as follows:
temp[0] is 12.3
temp[1] is 4.1
temp[2] is 0
temp[3] is 0
temp[4] is 0
Cont….
If the number of initializers is greater than the size of
the array then, the compiler will report an error. For
example:
int num[5] = {1, 2, 3, 4, 5, 6, 7, 8} // error
Multi-dimensional Arrays in C