Rabu, 21 Oktober 2015

Array in C Programming Languange

Array In C

     Array - when you want to store a collection of data, when the numbers are too many. we can simplify it using array. all arrays consist of contiguous memory locations. to declaring arrays, you must type the arrayname and arraysize by this following :
int ArrayName [arraysize];

but something that you must know are the arraysize must be an integer constant and more than zero and you can replace int with any valid c data type. for example :
int array[6]={1, 3, 4, 5, 7, 9}
the output will be :
       [1]             [3]           [4]             [5]           [7]             [9]
    array[0]   array[1]    array[2]    array[3]    array[4]    array[5]

you can also initialized array by following this source code:
int array[ ]={1, 3, 4, 5, 7, 9} // the output will be the same

something to remeber using array:
if you declared array consist of 6 numbers ( e.g array[6]) you can only use from array[0] to array[5]. you cannot use the element array [6] or more. it will cause a fatal error during program execution. but compiler will not show this error.

how to pass array?
in c programming, array can be passed to a function as argument. example :
#include <stdio.h>

void passing (int x)
   {
   printf ("%d\n", x);
   }

int main ()
{
int array[5]={1, 2, 3, 4, 5}; // array[0]=1, array [1]=2, array [2]=3, array [3]=4, array [4]=5
passing (array[3]); // passing array element array[3] only
}

the output will be :
4

after you know how to passed array, now i will give you simple example of an array :
#include <stdio.h>

int main ()
{
int n [10]; // this array will consist of 10 integers
for ( int x = 0; x < 10; x++)
{
n [x] = x + 10 ; // this will set element of x, x + 10
}

for (int y = 0; y < 10; y++)
{
printf("array[%d] = %d \n", y, n[y]);
}
return 0;
}

if when you compile it and error,it's not because you have a wrong program. but it's because the compiler. we cannot use for(int ......). so we need to change it into:

#include <stdio.h>

int main ()
{
int n [10]; // this array will consist of 10 integers
int x,y; // this is the different
 
for ( x = 0; x < 10; x++) // this is the different
{
n [x] = x + 10 ; // this will set element of x, x + 10
}

for (y = 0; y < 10; y++) // this is the different
{
printf("array[%d] = %d \n", y, n[y]);
}
return 0;
}

ok then the otput must be like this :
array [0] = 10
array [1] = 11
array [2] = 12
array [3] = 13
array [4] = 14
array [5] = 15
array [6] = 16
array [7] = 17
array [8] = 18
array [9] = 19

Note:
actually, array have 2 kind of array, 1-dimensional array and multidimensional array. the things that i have already explained to you is 1-dimensional array. in multidimensional array it will be more complex. i think you must learned about this first before you go. thanks :)