C Arrays

Discussion in 'C' started by msfq17a, Dec 30, 2013.

  1. Array is a data structure consists of a group of elements of same data type. We can think it as collection of variable of similar data type.

    Array prototype:

    Code:
    Data_type  array_name[array_size]
    Example:

    Suppose you have a team of 10 employees. Id is given for every employee. You want to store id, age and salary of each employee. How will you do that? From the concept of variable, you can declare 10 variables to store individual id, like: intemployeeId0, employeeId1, employeeId2, employeeId3, employeeId4, employeeId5, employeeId6, employeeId7, employeeId8, employeeId9;

    Isn’t that a hazard? You are declaring ten variables only for storing ten ids.

    It is the case where array facilitates you. Instead of ten variables, you can declare only one variable and store the same type of data in it.

    Code:
    int employeeId[10];
    Here, employeeId is an array of integer type of size 10.

    Array Indexing:

    So, if array is able to address different data of same type with same variable name, how does it maintain it? Indexing does the task. For the array declared above, every employee id can be accessed by the index of the array. The elements are: employeeId[0], employeeId[1], employeeId[2], employeeId[3], employeeId[4], employeeId[5], employeeId[6], employeeId[7], employeeId[8], employeeId[9]

    0,1,2…9 are the index of individual element. If the size of the array is n, then the index of array elements are from 0 to n-1.

    You can use array of age and salary of the employees as well.

    Code:
    int  employeeAge[10], float employeeSalary[10]
    Array Memory Allocation:

    The whole array is stored in a single contiguous memory block. Let, you have an array of integer:

    Code:
    int employeeId[10];
    If size of an integer is 2 byte, then 20(10*2) bytes will be required to store this array in memory and these 20 bytes must be contiguous.

    [​IMG]

    Address of the first element is called the base address of the array. Address of ith element of the array can be achieved by following formula:

    Address of i element = Address of base + size of element * i;

    Array initialization



    There are different ways to assign values to elements of an array .
    • Static initialization
    • Assigning values from Standard Input
    • Default Array initialization
    1. Static initialization:

    Code:
    int employeeAge[10] = {35,30,30,30,28,28,25,34,35,40};
    2. Assigning values from Standard Input:

    Suppose you have an array for age of employee, int employeeAge[10] . You want to take input and store the value in the array. You can use for loop to initialize the array.
    Code:
    int employeeAge[10], count, totalScore = 0;
    
    for(count = 0; count < 10; count++)
    {
    	printf("Enter Age: employeeAge[%d]:", count);
    	scanf("%d",& employeeAge[count]);	
    }
    
    3. Default Array initialization:
    Code:
    int main()
    {
        int arr [5] = {20};
        int count;
        for(count = 0; count < 5; count++)
        {
            printf("%d\n", arr [count]);
        } 
    }
    
    Output:
    Code:
    20
    0
    0
    0
    0
    
    Here, array size is 5. But we have initialized it with only one value {20}, instead of five. So,
    first element of the array, arr[0] get initialized with 20 and other elements are initialized with 0.

    Accessing array elements



    Suppose you have an array, which is initialized. Now you want to see the value of each element. Here is an example for doing this stuff:
    Code:
    int main()
    {
    	int count;
    	int employeeAge[10] = {35,30,30,30,28,28,25,34,35,40};
    	printf("here is the individual age of employees:\n");
    	for(count = 0; count < 10; count++)
    	{
    		printf("employee[%d]: %d\n", count,employeeAge[count]);
    	}
    } 
    

    Passing Arrays to Function



    There are two ways of doing this:
    1. Array element as parameter
    2. Whole array as parameter
    1. Array element as parameter

    If you want to send some element of an array to a function, you can specify the elements by their index. In the example given below, 1st and 2nd element of the array byteVal[8] are sent to addVal function. The parameters are byteVal[0] and byteVal[1]. Accordiingly, 2nd and 5th element of byteVal[8] array are sent to subtractVal function.
    Code:
    int addVal(int x, int y)
    {
    	int sum = x+y;
    	return sum;
    }
    int subtractVal(int x, int y)
    {
    	int sub = x - y;
    	return sub;
    }
    int main()
    {
    	int byteVal[8] = {40,10,250,5,190,150,80,200};
    	int addByteVal, subByteVal;
    	 
    	addByteVal = addVal(byteVal[0],byteVal[1]);
    
    	subByteVal = subtractVal(byteVal[1],byteVal[4]);
    
    	printf("addition result : %d, subtraction result: %d",addByteVal, subByteVal);
    }
    
    2. Whole array as parameter

    So, when you want to call a function with an array as argument, just write the array name. The parameter passing procedure is just like the variable passing. The difference is in how the called function receives the array. To receive an array, you have to write the array name with array notation[]. It means that the received parameter is an array. You do not need to define the array size here.

    In the example given below, array byteVal is passed to the function showByteVal by only the name and received with an integer array, int getByte[] .
    Code:
    int showByteVal(int getByte[])
    {
    	int count;
    	printf("Array of byte value recieved. Values are:\n");
    	for(count = 0; count < 8; count++)
    	{
    		printf("%d\n",getByte[count]);
    	}
    }
    
    int main()
    {
    	int byteVal[8] = {40,10,250,5,190,150,80,200};
    	showByteVal(byteVal);
    }
    
    Why array passed to function changes its value?

    Suppose you send an array or any array elements to a function. Then you make some operation on the array elements and change value of the element. When the function returns, the data passed as array parameter is changed. Let’s see:
    Code:
    int changeByteVal(int getByte[])
    {
          int count;
          printf("Array of byte value recieved. Values are:\n");
          for(count= 0; count < 8; count++)
          {
                printf("%d\n",getByte[count]);
          }
     
          getByte[0] = getByte[1] + getByte[2];
    }
     
    int main()
    {
          int loopCount;
          int byteVal[8] = {40,10,250,5,190,150,80,200};
          changeByteVal(byteVal);
          printf("returned from changeByteVal function. Now values are:\n");
          for(loopCount= 0; loopCount < 8; loopCount++)
          {
                printf("%d\n",byteVal[loopCount]);
          }
    }
    
    Output:
    Code:
    Array of byte value received. Values are:
    40
    10
    250
    5
    190
    150
    80
    200
    returned from changeByteVal function. Now values are:
    260
    10
    250
    5
    190
    150
    80
    200
    
    In the above program the first element of byteVal array, byteVal[0] is initialized with value 40. The array is sent to changeByteVal function. Here, value of byteVal[0] has been changed to 260. When we return to caller function, we print the element of the array and experience that value of byteVal[0] is now 260.

    When an array is sent to a function, it is the base address of the array is sent. The base address received by the called function makes operation on the variables memory and so the original value gets changed. So, you will always get the changed value.

    2D Arrays



    Array can be multi dimensional. In this section, we will discuss about two-dimensional array.

    Prototype:

    Prototype of 2d array is:

    Code:
    DataType  arrayName [rowSize][columnSize]
    Think of an array of 2*2 dimension. It is declared as:

    Code:
    int matrix[2][2];
    Visualization is like this:

    [​IMG]

    Elements of this 2d array are:
    Code:
    matrix[0][0] = 0
    matrix[0][1] = 1
    matrix[1][0] = 2
    matrix[1][1] = 3
    
    Suppose you have three teams and every team contains five members. You want to store the age of each member of every team. Then you should declare a two dimensional array of 3*5 size.

    int memberAge[3][5]

    Here, 3 is team number and 5 is number of members of every team. You can initialize and access age of each member of each team by this 2d array.

    2D Array Initialization



    2d array is initialized in the same ways as array.
    1. Static initialization
    2. Assigning values from Standard Input
    3. Default Array initialization
    1. Static initialization:

    2d array can be statically initialized in 2 different ways:

    Way 1: int age[2][3]= {40,35,30,42,33,25};

    Way 2: int age[2][3] = {{40,35,30},{42,33,25}};

    2. Assigning values from Standard Input:

    How to initialize every element of a 2d array from standard input? Let’s see:
    Code:
    #define ROWSIZE 2
    #define COLSIZE 3
    int main()
    {
    	int row, col;
    	int age[ROWSIZE][ COLSIZE];
    	for(row = 0; row < ROWSIZE; row++)
    		for(col =0; col < COLSIZE; col++)
    			scanf("%d",&age[row][col]);
    }
    
    3. Default Array initialization

    This is same as single dimension array where the specified values are initialized and rest is all 0.

    Accessing 2d array elements



    If you have an initialized 2d array and want to get the values, you can act like this:
    Code:
    #define ROWSIZE 2
    #define COLSIZE 3
    int main()
    {
    	int row, col;
    	int age[ROWSIZE][ COLSIZE] = {40,35,30,42,33,25};
    
    	for(row = 0; row < ROWSIZE; row++)
    		for(col =0; col < COLSIZE; col++)
    			printf("Index[%d][%d] : %d\n",row,col,age[row][col]);
    }
    

    Use of Arrays



    Array is used for different operations. In some searching and sorting algorithm, array is very important and useful. We are going to watch how array facilitates linear search operation.

    Linear search:

    Let you have a list of roll numbers who have passed in the last exam. Now, some students come to you, tell their rolls and ask you whether they are in the pass list. The list is not sorted in increasing or decreasing order yet. How will you search their roll? For every student, you will start from the beginning of your list and search every element of the list throughout the end. If roll number is found, you will stop and tell that he/she has passed. Otherwise you would inform the negative result. This type of searching is called linear search.
    Here is a way of implementing linear search using array:
    Code:
    #define SIZE 4
    int main()
    {
    	int i,searchNum;
    	int arrayOfNum[SIZE];
    	int flag = 0;
    	int iterate = SIZE - 1;
    	printf("Enter %d elements of array:\n",SIZE);
    	
    	for(i =0; i < SIZE; i++)
    	{
    		printf("\narrayOfNum[%d]:",i);
    		scanf("%d",&arrayOfNum[i]);
    	}
    	printf("Enter the element you want to search:");
    	scanf("%d",&searchNum);
    	for(i = 0; i < SIZE; i++)
    	{
    		if(arrayOfNum[i] == searchNum)
    		{
    			printf("%d found in arrayOfNum[%d]",searchNum,i);
    			flag = 1;
    			break;
    		}
    	}
    	if(flag == 0)
    		printf("Not found\n");
    }
    
    Use of 2d Array

    2d array can be used for different advanced operations. Out of them, most common example is matrix operation. We can perform any matrix operation using 2d arrays. We are going to explain matrix addition operation using 2d arrays.

    Matrix Addition

    Suppose A and B are two matrices. We have to perform matrix addition and save the result in another matrix. Let the new matrix is C. So, the operation we are going to perform is:

    C = A + B.
    Code:
    #define ROWSIZE 2
    #define COLSIZE 3
    
    int main()
    {
    	int row, col;
    	int A[ROWSIZE][COLSIZE],B[ROWSIZE][COLSIZE],C[ROWSIZE][COLSIZE];
    
    	printf("Enter elements of matrix A:\n");
    	for(row = 0; row < ROWSIZE; row++)
    		for(col =0; col < COLSIZE; col++)
    		{
    			printf("\nA[%d][%d]:",row,col);
    			scanf("%d",&A[row][col]);
    		}
    
    	printf("Enter elements of matrix B:\n");
    	for(row = 0; row < ROWSIZE; row++)
    		for(col =0; col < COLSIZE; col++)
    		{
    			printf("\nB[%d][%d]:",row,col);
    			scanf("%d",&B[row][col]);
    		}
    
    	printf("After performing operation C = A+B:\n");
    
    	for(row = 0; row < ROWSIZE; row++)
    		for(col =0; col < COLSIZE; col++)
    		{
    			C[row][col] = A[row][col] + B[row][col];
    			printf("C[%d][%d] : %d\n",row,col,C[row][col]);
    
    		}
    }
    

    Advantages of Arrays


    1. Group of similar objects can be used by single variable and different index.
    2. Multi dimensional arrays is possible
    3. Accessing array element is not sequential and so operations like searching, sorting are faster.

    Disadvantages of Arrays


    1. Array size is static in C. Allocated memory cannot be increased or decreased with arrays and so size of array has to to be known before any operation. For dynamic size we have to be using pointers.
    2. Removing array elements from between means the complete array needs to be shifted which is a costly operation.
     
    Last edited by a moderator: Jan 21, 2017

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice