Monday 29 September 2014

Array in C

ARRAY [ ]

Hello friends,
Today I am going to discuss Array in programming C.

Overview :

C language provides facility to design set of similar data types called array. So, what is array ?
Array is group of variables of same datatypes. When we need multiple variable of same datatype, array can be used.

Array :

Suppose you are collecting percentage marks of 100 student. Then there are two possibility.
1) we take 100 variable to store percentage marks of 100 student.
or 2) we take single variable named marks, which is capable to store all 100 percentage marks of 100
    Students.

obviously second one is better. Because in first case if we want to sort or one by one access the value of marks of each student then it will become very hard task to do. But if we use array here than it becomes easy. Let’s see how?

How to declare array ?

int mark[100];

here we create array of 100 variable of type integer. And mark is name of that array.

we can expand mark[100] like this :
mark[0], mark[1], mark[2] ….. ,mark[99].

Value written within bracket “[]”  shows number of element. 100 is number of element in our case.
note that array position starts with 0th location.

let’s make array smaller to take some example. I am taking array to store marks of 5 student. Then I will declare array as,

int mark[5].

now how to scan and print array element ?
For that we have to take another integer variable as index value of array.

int i;
for(i=0 ; i<5 ; i++)
scanf(“ %d ” ,&mark[i]);

Now take random marks, 10 20 40 55 35.

for(i=0 ; i<5 ; i++)
printf(“student%d = %d\n”,i+1,mark[i]);

o/p :
student1 = 10;
student2 = 20;
student3 = 40;
student4 = 55;
student5 = 35;

so if we want to get value of third element from the array into variable z, we can get it by,
z = mark[2];

note: here I am writing 2 and not 3. Because mark[0] is first element of array. So, mark[2] becomes third element.

Another way of Declaration :

We can assign value to array at declaration time too.
int mark[5] = {10, 20, 40, 55, 35};

Note that if we are assigning value at declaration time, it doesn’t require to give size of array. What I am saying is, we can write above statement as,
int mark[] = {10, 20, 40, 55, 35};

but if you are not assigning value at declaration time than we have to specify the length of array. Because we have to tell compiler that howmany value i am going to store in my array and according to that compiler will give use memory space.

note that array elements are stored in contiguous memory location.

If we are taking array with 8 element (ex. Mark[8]) and we assign value upto 5th element, but we are printing value of array till 8th position. Than what will be printed for 6th, 7th and 8th element ?
Answer : it will print any garbage value. Or zero in most of case.

char array :

char arr[]={‘a’ , ‘b’, ‘c’, ‘d’, ‘e’};

declaration is same as integer array, but when we are giving character value to array we have to write character in single quotation.

Array for string :

we can also assign whole string to array.

Char arr[] = “Hello_World”;

How this string appears in array ? -> { ‘H’, ’e’, ‘l’, ‘l’, ‘o’, ‘_’, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘\0’ };

Look at the last element. ‘\0’ is called null character. It is here to indicate the end of string.

Now lets see example for this,

main()
{
            char arr[10];
            printf(“Enter String : ”);
            scanf(“%s”,arr);

            printf(“\n string entered by user : %s ”,arr);
}

o/p:
Enter String : hello
String entered by user : hello

Here in scanf we have used arr and note &arr.
Because by adding ‘&‘ , we gets the address of variable where we want to store our data.
ex.  
     int a;
     scanf(“ %d ”, &a);

here ‘ &a ’ is address of variable a. (you will understand this easily once you learn pointer.).
back to our program, array name is pointer to the first element of array or string. So in our case arr is pointer to ‘h’ or we can say arr has address of ‘ h ’. so as per low second argument of scanf should be address and in our case “ scanf(“ %s ”,arr) “  arr itself is address.


Passing array to Function :

How to pass array to function ?

Let’s take same array mark[5] having value 10, 20, 40, 55, 35. And we are passing it to add function which will add all element of array. So we have to pass full array and length of array.

#include<stdio.h>

int add(int arr[], int);
main()
{
            int mark[] = {10, 20, 40, 55, 35};
            int ans;
            ans = add(mark,5);
            printf(“Ans = %d\n”, ans);
}
int add(int arr[],int len)
{
            int i,num = 0;
            for(i = 0 ; i <len ; i++)
            {
                        num = num + arr[i];
            }
            return(num);
}

o/p :
Ans = 160.

To understand what we are doing here, you should be aware with pointer. Array is similar to pointer. Array name itself is pointer to first element of array. So we can pass only array name to the function and function will get the address of first element of passed array and as you know array elements are stored in contiguous location, function can access full array.

Don’t get confused. If you are unable to understand this than leave it. First understand pointer to array and than again read above lines. I will give link for pointer to array at the end of discussion.

Now let me take another example.
Now we will change the value of second element of array in called function and then we will check whether the second element of mark array in main function is changed or not.

#include<stdio.h>

void func(int arr[], int);
main()
{
            int mark[] = {10, 20, 40, 55, 35};
           
            printf(“second element = %d before \n”, mark[1]);
add(mark,5);                                                    //calling a function
            printf(“second element = %d after \n”, mark[1]);
}
Void func(int arr[],int len)
{
            arr[1] = arr[1] + 10;
}

Run this program and you will get second element becomes 30 from 20.

o/p :
second element = 20 before
second element = 30 after

value is changed because we are not passing value of array element, but we are passing address of array element.

So array is all about pointer and address.

At this stage i am going to stop this discussion on array. Still many thing remains in array part. I will update my blog soon.


If anyone have query, question or suggestion please write it bellow in the comment box.

To know more on another important topic in c “POINTER

To know more on another important topic in c “C PREPROCESSOR

Are you a Fresh Programmer?? Join facebook group to be a perfect programmer.

https://www.facebook.com/groups/121611948548929/

Thanks,

Akash Patel.


No comments:

Post a Comment