Array in C'

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

Array in C

C programming language provides a data structure called the array, which can store a fixed-size sequential collection of elements of the same type. What is Array Before we start explain what is an array, you should understand why array concept is comes? How it is requires in C?

#include<stdio.h> int main() { int r; r=1; r=2; printf("The value of r = %d",r); getch(); return 0; } The output of above program would be: The value of r = 2 So, you can understand that when the value 2 is assigned into r, the earlier value of r (i.e. 1) is lost. Thus the ordinary variables are capable of holding only one value at a time. What we do if we would want to store more than one value at a time in a single variable? For Example suppose we have to store the roll numbers of the 100 students, in such a case we have two options to store these roll numbers in memory: We have to declare 100 variables named as roll1,roll2,roll3,.roll100 which is very difficult job. Construct one variable (called array or subscripted variable) capable of storing or holding all the hundred values in the contiguous memory which has 100 blocks , can be accessed by single variable name.

Er. Pankaj Kapoor

Page 1

Array in C
What is an Array
Array is a collection of similar values. The values in an array are called as 'elements of an array.' These elements are accessed by numbers called as 'subscripts or index numbers. An array is also known as a subscripted variable. Before using an array, its type and dimension must be declared. The array elements are always stored in contiguous memory locations. This is a very important feature of array. Thus, an array is collection of similar elements. These similar elements could be all ints, or all floats, or all chars.

Types of an Array
1. One / Single Dimensional Array 2. Two Dimensional Array

Declaring Single Dimension Arrays Arrays can be declared using any of the data types available in C. Array size must be declared using constant value before initialization. Array having only one subscript variable is called One-Dimensional array or Linear Array. A single dimensional array will be useful for simple grouping of data that is relatively small in size. You can declare a single dimensional array as follows:

Syntax: <data-type> <array_name> [size]; Example: int a[3]; Total Size (in Bytes): total size = length of array * size of data type
In above example, a is an array of type integer which has storage size of 3 elements. The total size would be 3 * 2 = 6 bytes. Let us understand this with the help of an example.

/* Program to demonstrate one dimensional array. #include <stdio.h> #include <conio.h> void main() { int arr[3], i;; clrscr(); printf("\n\t Enter three numbers : "); for(i=0; i<3; i++)
Er. Pankaj Kapoor Page 2

Array in C
{ scanf("%d", &arr[i]); // read array } printf("\n\n\t Numbers are : "); for(i=0; i<3; i++) { printf("\t %d", arr[i]); // print array } getch(); }
Here, int specifies the type of the variable, just as it does with ordinary variables and the word arr specifies the name of the variable. The [3] however is new. The number 3 tells how many elements of the type int will be in our array. This number is often called the dimension of the array. The bracket ( [ ] ) tells the compiler that we are dealing with an array.

Accessing Array Elements Given the declaration above of a 3 element array the compiler reserves space for 3 consecutive integers and accesses these values using an index/subscript that takes values from 0 to 2. The first elementin an array in C always has the index 0, and if the array has n elements the last element will have the index n-1. An array element is accessed by writing the identifier of the array followed by the subscript in square brackets. Thus to set the 3th element of the array above to 25 the following assignment is used: arr [2] = 25; Note that since the first element is at index 0, then the ith element is at index i-1. Hence in the above the 3th element has index 2. Putting Data into an Array When an array is declared, a garbage value is stored in it. Thus, accessing the value of array elements without defining it will give garbage value. for(i=0;i<3;i++){ scanf(%d,&arr[i]) } The above for loop accepts the value from the user and stores it in an array. The array that was declared before is getting defined here. Thus, First value corresponding to 1st iteration of for loop is stored in the element arr[0] Er. Pankaj Kapoor Page 3

Array in C
Second value corresponding to 2nd iteration of for loop is stored in the element arr[1] Third value corresponding to 3rd iteration of for loop is stored in the element arr[2] In scanf( ) function, we have used the address of operator (&) on the element arr[i] of the array, just as we have used it earlier on other variables. In so doing, we are passing the address of this particular array element to the scanf( ) function, rather than its value; which is what scanf( ) requires. Reading Data from an Array for(i=0;i<3;i++){ printf(%d\t,arr[i]) } The above for loop displays the value stored in the array. Thus, 1st iteration displays value stored in arr[0] 2nd iteration displays value stored in arr[1] 3rd iteration displays value stored in arr[2] In the above program, we have used data type int for the array. Hence it is called integer array. We can also declare array as float. But then it will contain float values. An array element can only hold one type of data i.e. either integer or float or character.

Array Initialization
Consider this program, void main(){ int arr[3]; arr[0] = 1; arr[1] = 2; arr[2] = 3; } An array can be defined as follows: int arr[3]={1,2,3}; i.e., arr[0] --> 1 arr[1] --> 2 arr[2] --> 3 An array can also be defined as: int arr[]={1,2,3};

int primes[] = {1, 2, 3, 5, 7, 11, 13}; Compiler Counts the Number Of Elements Written Inside Pair of Braces and Determines the Size of An Array. After counting the number of elements inside the braces, The size of array is considered as 5 during complete execution. This type of Initialization Scheme is also called as Compile Time Initialization For example: Er. Pankaj Kapoor Page 4

Array in C
int primes[10] = {1, 2, 3, 5, 7};

would reserve space for a ten element array but would only initialize the first five elements and remaining with initial value 0.
MEMORY ALLOCATION :

Fig: Memory allocation for one dimensional array


Let us suppose that base address of this array is 1000. So value 1 is stored at memory location 1000. Since it is integer array, 16 bit C compiler will assign 2 bytes of memory for its storage. Hence next value i.e. 2 will be stored at location 1002. Similarly, 3 will be stored at location 1004.

How Array Element is randomly accessed ?


1. Array elements are randomly accessed. 2. Array Can be accessed using Array-Name and Subscript Variable written inside pair of Square Brackets []. 3. Example arr[3] = Third Element of Array
arr[5] arr[8] = Fifth Element of Array = Eighth Element of Array

We know that array is declared like this int arr[] = { 51,32,43,24,5,26};


So already we have base address of Array Consider *arr will gives Zeroth Element from Array. Similarly *(arr+0) will also yields same result.

Note :

Generally Accessing a[i] means retrieving element from address (arr + i) .


Observations and Conclusion : arr[i] = 5
*(arr+i) = 5
Page 5

Er. Pankaj Kapoor

Array in C
*(i+arr) i[arr] = 5 = 5

all of the above notations yields same result. Lets Prove it #include< stdio.h> #include< conio.h>

void main() { int arr[] = { 51,32,43,24,5,26}; int i; for(i=0;i<=5;i++) printf("\n%d %d %d %d",arr[i],*(i+arr),*(arr+i),i[arr]); getch(); }

Output : 51 51 51 51
32 32 32 32 43 43 43 43 24 24 24 24 5 5 5 5 26 26 26 26

1. If we specify the size of array as N then we can access elements upto N-1 but in C if we try to access elements after N-1 i.e Nth element or N+1th element then we does not get any error message. 2. In C there is no check to see if the subscript used for an array exceeds the size of the array. Data entered with a subscript exceeding the array size will simply be placed in memory outside the array; This will lead to unpredictable results, to say the least, and there will be no
Er. Pankaj Kapoor Page 6

Array in C
error message to warn you that you are going beyond the array size. In some cases the computer may just hang. 3. Process of Checking the extreme limit of array is called Bound Checking and C does not perform Bound Checking. 4. If the array range exceeds then we will get garbage value as result.
main( ) { int num[4], i ; for ( i = 0 ; i <= 10 ; i++ ) num[i] = i ; }

Er. Pankaj Kapoor

Page 7

Array in C
2. Multi Dimensional Array :
1. Array having more than one subscript variable is called Multi-Dimensional array. 2. Multi Dimensional Array is also called as Matrix.
Syntax :

<data-type> <array_name> [row_subscript][column-subscript];


Example : Two Dimensional Array

int a[3][3] = { 1,2,3 5,6,7 8,9,0 };

Er. Pankaj Kapoor

Page 8

Array in C
Application Of Array :
Array is used for different verities of applications. Array is used to store the data or values of same data type. Below are the some of the applications of array: 1. Stores Elements of Same Data Type 2. Array used for maintaining multiple variable names using single name 3. Array can be used for Sorting Elements 4. Array can Perform Matrix Operation 5. Array can be used in CPU Scheduling 6. Array can be used in Recursive Function

Er. Pankaj Kapoor

Page 9

Array in C
Limitations of Array in C Programming : Array is very useful which stores multiple data under single name with same data type. Following are some listed limitations of Array in C Programming. 1. Static Data 2. Can hold data belonging to same Data types 3. Inserting data in Array is Difficult 4. Deletion Operation is difficult 5. Bound Checking 6. Shortage of Memory (Size of the array must be known in advance). 7. Wastage of Memory

Er. Pankaj Kapoor

Page 10

Array in C
Two-Dimensional Arrays:
The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays. The array which is used to represent and store data in a tabular form is called
as 'two dimensional array.' Such type of array specially used to represent data in a matrix form. n array can be 1-Dimensional, 2-Dimensional, 3-Dimensional and so on. In this topic, we will discuss 2-Dimensional arrays in C Programming Language. The following syntax is used to represent two dimensional array.

Syntax: <data-type> <array_nm> [row_subscript][column-subscript]; Example: int a[3][3];


In above example, a is an array of type integer which has storage size of 3 * 3 matrix. The total size would be 3 * 3 * 2 = 18 bytes. Let us understand what two dimensional arrays are. Consider the following matrix. 11 12 13 A= 14 15 16 17 18 19 The above mentioned matrix is 3 by 3. The matrix elements can be accessed using the formula A[m,n], where m represents row number and n represents column number. Thus, the first element i.e. 11 is represented as A[0,0]. Similarly, A[0,1] = 12 A[0,2] = 13 A[1,0] = 14 A[1,1] = 15 and so on. The 2-dimensional array follows the similar concept. So we can declare 2-dimensional array for above matrix as A[3][3]. Initialising a 2-Dimensional Array We can define 2-dimensional array as follows. int A[3][3]={ {11,12,13}, {14,15,16}, {17,18,19} } Element 11 can be referred as A[0][0] Element 12 can be referred as A[0][1] Element 13 can be referred as A[0][2]

Er. Pankaj Kapoor

Page 11

Array in C
Element 14 can be referred as A[1][0] Element 15 can be referred as A[1][1] and so on. The above mentioned method increases the readability of the matrix. int A[][] and A[3][] are invalid. We cannot skip the column index in 2-D arrays. int A[][3] and A[3][3] are both valid. The nested braces, which indicate the intended row, are optional. The following initialization is equivalent to previous example:

int a[3][3] = {11,12,13,14,15,16,17,18,19};

Accessing Array Elements


To access every 2-D array we require 2 subscript variables. i refers the Row number and j refers Column number. a[0][0] refers element belonging to zeroth row and zeroth column accept and print 33 Matrix from user.

#include<stdio.h> #include<conio.h> void main() { int i,j,a[3][3]; /* i = For Counting Rows j = For Counting Columns */ /* Accept 9 elements from user */ for(i=0;i<3;i++) for(j=0;j<3;j++) { printf("nEnter the a[%d][%d] = ",i,j); scanf("%d",&a[i][j]); } /* Print 9 elements */ for(i=0;i<3;i++) { for(j=0;j<3;j++) printf("%dt",a[i][j]); printf("n"); } getch();
Er. Pankaj Kapoor Page 12

Array in C
}
For every value of row Subscript, the column subscript incremented from 0 to n-1 columns. i.e For zeroth row it will accept zeroth, first, second column ( a[0][0], a[0][1], a[0][2]) elements. In next iteration Row number will be incremented by 1 and the column number again initialized to 0.

a[i][j]

== Element From i-th Row and j-th Column

Memory Representation
2-D arrays are Stored in contiguous memory location row wise. 3 X 3 Array is shown below in the first Diagram. Consider 33 Array is stored in Contiguous memory location which starts from 4000. Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next memory location i.e Elements stored row-wise After Elements of First Row are stored in appropriate memory location, elements of next row get their corresponding memory locations. This is integer array so each element requires 2 bytes of memory.

Er. Pankaj Kapoor

Page 13

Array in C

Element a[0][0] a[0][1] a[0][2] Basic Memory Address Calculation:

Memory Location 4000 4002 4004 4006 4008 4010 4012 4014 4016

a[0][1] = a[0][0] + Size of Data Type

a[1][0] a[1][1] a[1][2] a[2][0] a[2][1] a[2][2]

Multidimensional or the Three Dimensional Array The Multidimensional Array are used for Representing the Total Number of Tables of Matrix. A Three dimensional Array is used when we wants to make the two or more tables of the Matrix Elements for Declaring the Array Elements we can use following systex: int a[3][4][2]; In this first 3 represents the total number of Tables and the second 4 represents the total number of rows in the each table and the third 2 represents the total number of Columns in the Tables. So this makes the 3 Tables having the four rows and the two columns. However, example of initializing a three-dimensional Er. Pankaj Kapoor Page 14 an

Array in C
array will consolidate your understanding of subscripts: int arr[3][4][2] = { { { { { { }, { { { { { }, { { { { { } } ; A three-dimensional array can be thought of as an array of arrays of arrays. The outer array has three elements, each of which is a two-dimensional array of four onedimensional arrays, each of which contains two integers. 8, 7, 3, 5, 9 2 4 1 }, }, }, }, 7, 3, 5, 2, 6 4 3 3 }, }, }, } 2, 7, 3, 5, 4 8 4 6 }, }, }, }

Er. Pankaj Kapoor

Page 15

Array in C
/* Write a C program that uses functions to perform the following: i) Addition of Two Matrices ii) Multiplication of Two Matrices */ #include<stdio.h> } void main() { int ch,i,j,m,n,p,q,k,r1,c1,a[10][10],b[10][10],c[10][10]; clrscr(); printf("************************************"); printf("\n\t\tMENU"); printf("\n**********************************"); printf("\n[1]ADDITION OF TWO MATRICES"); printf("\n[2]MULTIPLICATION OF TWO MATRICES"); printf("\n[0]EXIT"); printf("\n**********************************"); printf("\n\tEnter your choice:\n"); scanf("%d",&ch); if(ch<=2 & ch>0) { printf("Valid Choice\n"); } switch(ch) { case 1: printf("Input rows and columns of A & B Matrix:"); scanf("%d%d",&r1,&c1); printf("Enter elements of matrix A:\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&a[i][j]); } printf("Enter elements of matrix B:\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) scanf("%d",&b[i][j]); { printf("Matrices cannot be multiplied."); } /*end else*/ printf("Resultant of two matrices:\n"); write_matrix(c,m,q); } /*end if*/ else } case 2: printf("Input rows and columns of A matrix:"); scanf("%d%d",&m,&n); printf("Input rows and columns of B matrix:"); scanf("%d%d",&p,&q); if(n==p) { printf("matrices can be multiplied\n"); printf("resultant matrix is %d*%d\n",m,q); printf("Input A matrix\n"); read_matrix(a,m,n); printf("Input B matrix\n"); /*Function call to read the matrix*/ read_matrix(b,p,q); /*Function for Multiplication of two matrices*/ printf("\n =====Matrix Multiplication=====\n"); for(i=0;i<m;++i) for(j=0;j<q;++j) { c[i][j]=0; for(k=0;k<n;++k) c[i][j]=c[i][j]+a[i][k]*b[k][j]; break; } printf("\n =====Matrix Addition=====\n"); for(i=0;i<r1;i++) { for(j=0;j<c1;j++) printf("%5d",a[i][j]+b[i][j]); printf("\n");

Er. Pankaj Kapoor

Page 16

Array in C
break; case 0: printf("\n Choice Terminated"); exit(); break; default: printf("\n Invalid Choice"); } getch(); } /*Function read matrix*/ int read_matrix(int a[10][10],int m,int n) { int i,j; for(i=0;i<m;i++) } } return 0; /*Function to write the matrix*/ int write_matrix(int a[10][10],int m,int n) { int i,j; for(i=0;i<m;i++) { for(j=0;j<n;j++) printf("%5d",a[i][j]); printf("\n"); for(j=0;j<n;j++) scanf("%d",&a[i][j]); return 0; }

Er. Pankaj Kapoor

Page 17

You might also like