ARRAY IN C
• An array is defined as the collection of similar type of data items stored at
contiguous memory locations. Arrays are the derived data type in C
programming language which can store the primitive type of data such as
int, char, double, float, etc. It also has the capability to store the collection
of derived data types, such as pointers, structure, etc. The array is the
simplest data structure where each data element can be randomly
accessed by using its index number.
• C array is beneficial if you have to store similar elements. For example, if
we want to store the marks of a student in 6 subjects, then we don't need
to define different variables for the marks in the different subject. Instead
of that, we can define an array which can store the marks in each subject
at the contiguous memory locations.
• By using the array, we can access the elements easily. Only a few lines of
code are required to access the elements of the array.
Properties of Array
The array contains the following properties.
• Each element of an array is of same data type and
carries the same size, i.e., int = 4 bytes.
• Elements of the array are stored at contiguous memory
locations where the first element is stored at the
smallest memory location.
• Elements of the array can be randomly accessed since
we can calculate the address of each element of the
array with the given base address and the size of the
data element.
Advantage of C Array
1) Code Optimization: Less code to the access the
data.
2) Ease of traversing: By using the for loop, we can
retrieve the elements of an array easily.
3) Ease of sorting: To sort the elements of the array,
we need a few lines of code only.
4) Random Access: We can access any element
randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of
declaration of the array, we can't exceed the limit. So, it
doesn't grow the size dynamically like LinkedList which
we will learn later.
Declaration of C Array
We can declare an array in the c language in the following way.
data_type array_name[array_size];
Now, let us see the example to declare the array.
int marks[5];
Here, int is the data_type, marks are the array_name, and 5 is
the array_size.
Initialization of C Array
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;
#include<stdio.h> for(i=0;i<5;i++){
int main(){ printf("%d \n",marks[i]);
int i=0; }//end of for loop
int marks[5];// return 0;
declaration of array }
marks[0]=80;//
initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
C Array: Declaration with
Initialization
We can initialize the c array at the time of declaration.
Let's see the code.
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define the
size. So it may also be written as the following code.
int marks[]={20,30,40,50,60};
#include<stdio.h>
int main()
{
int i=0;
int marks[5]={20,30,40,50,60};//
declaration and initialization of array
//traversal of array
for(i=0;i<5;i++)
{
printf("%d \n",marks[i]);
}
return 0;
}
Sorting an array a[i] = a[j];
#include<stdio.h> a[j] = temp;
void main () }
{ }
int i, j,temp; }
int a[10] = { 10, 9, 7, 101, 23 printf("Printing Sorted Element
, 44, 12, 78, 34, 23}; List ...\n");
for(i = 0; i<10; i++) for(i = 0; i<10; i++)
{ {
for(j = i+1; j<10; j++) printf("%d\n",a[i]);
{ }
if(a[j] > a[i]) }
{
temp = a[i];
//Find the largest and second largest {
#include<stdio.h> if(arr[i]>largest)
void main () {
{ sec_largest = largest;
int arr[100],i,n,largest,sec_largest; largest = arr[i];
printf("Enter the size of the array?"); }
scanf("%d",&n); else if (arr[i]>sec_largest && arr[i]
printf("Enter the elements of the arra !=largest)
y?"); {
for(i = 0; i<n; i++) sec_largest=arr[i];
{ }
scanf("%d",&arr[i]); }
} printf("largest = %d, second largest
largest = arr[0]; = %d",largest,sec_largest);
sec_largest = arr[1];
for(i=0;i<n;i++) }
Two Dimensional Array in C
The two-dimensional array can be defined as an array of
arrays. The 2D array is organized as matrices which can
be represented as the collection of rows and columns.
However, 2D arrays are created to implement a relational
database lookalike data structure. It provides ease of
holding the bulk of data at once which can be passed to
any number of functions wherever required.
Declaration of two dimensional
Array in C
The syntax to declare the 2D array is given below.
data_type array_name[rows][columns];
Consider the following example.
int twodimen[4][3];
Here, 4 is the number of rows, and 3 is the number of columns.
Initialization of 2D Array in C
In the 1D array, we don't need to specify the size of the
array if the declaration and initialization are being done
simultaneously. However, this will not work with 2D
arrays. We will have to define at least the second
dimension of the array. The two-dimensional array can be
declared and defined in the following way.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
#include<stdio.h>
int main()
{
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
//traversing 2D array
for(i=0;i<4;i++)
{
for(j=0;j<3;j++)
{
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
Storing elements in a matrix and printing it. }
printf("\
#include <stdio.h> n printing the elements ....\
void main () n");
{ for(i=0;i<3;i++)
int arr[3][3],i,j; {
for (i=0;i<3;i++) printf("\n");
{ for (j=0;j<3;j++)
for (j=0;j<3;j++) {
{ printf("%d\t",arr[i][j]);
printf("Enter a[%d] }
[%d]: ",i,j); }
scanf("%d",&arr[i][j]); }
}
Return an Array in C
What is an Array?
• An array is a type of data structure that stores a fixed-
size of a homogeneous collection of data. In short, we
can say that array is a collection of variables of the
same type.
• For example, if we want to declare 'n' number of
variables, n1, n2...n., if we create all these variables
individually, then it becomes a very tedious task. In
such a case, we create an array of variables having the
same type. Each element of an array can be accessed
using an index of the element.
• Let's first see how to pass a single-dimensional array to
Passing array to a function
#include <stdio.h>
void getarray(int arr[])
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[5]={45,67,34,78,90};
getarray(arr);
return 0;
}
Passing array to a function as a
pointer
#include <stdio.h>
void printarray(char *arr)
{
printf("Elements of array are : ");
for(int i=0;i<5;i++)
{
printf("%c ", arr[i]);
}
}
int main()
{
char arr[5]={'A','B','C','D','E'};
printarray(arr);
return 0;
}
Returning pointer pointing to the array
#include <stdio.h> int main()
int *getarray() {
{ int *n;
int arr[5]; n=getarray();
printf("Enter the elements in an a printf("\nElements of array are :");
rray : "); for(int i=0;i<5;i++)
for(int i=0;i<5;i++) {
{ printf("%d", n[i]);
scanf("%d", &arr[i]); }
} return 0;
return arr; }
}
In the above program, getarray() function returns a
variable 'arr'. It returns a local variable, but it is an illegal
memory location to be returned, which is allocated within
a function in the stack. Since the program control comes
back to the main() function, and all the variables in a
stack are freed. Therefore, we can say that this program
is returning memory location, which is already de-
allocated, so the output of the program is
a segmentation fault.
There are three right ways of returning an array to a
function:
•Using dynamically allocated array
•Using static array
•Using structure
Returning array by passing an array which is to be returned
as a parameter to the function.
#include <stdio.h> {
int *getarray(int *a) int *n;
{ int a[5];
n=getarray(a);
printf("Enter the elements in an ar printf("\nElements of array are :");
ray : "); for(int i=0;i<5;i++)
for(int i=0;i<5;i++) {
{ printf("%d", n[i]);
scanf("%d", &a[i]); }
} return 0;
return a; }
}
int main()
Returning array using malloc() return p;
function. }
#include <stdio.h> int main()
#include<malloc.h> {
int *getarray() int *ptr;
{ ptr=getarray();
int size; int length=sizeof(*ptr);
printf("Enter the size of the array : "); printf("Elements that you have entered
scanf("%d",&size); are : ");
int *p= malloc(sizeof(size)); for(int i=0;ptr[i]!='\0';i++)
printf("\ {
nEnter the elements in an array"); printf("%d ", ptr[i]);
for(int i=0;i<size;i++) }
{ return 0;
scanf("%d",&p[i]); }
}
Using Static Variable }
#include <stdio.h> int main()
int *getarray() {
{ int *ptr;
static int arr[7]; ptr=getarray();
printf("Enter the elements in an arr printf("\
ay : "); nElements that you have entered are
for(int i=0;i<7;i++) :");
{ for(int i=0;i<7;i++)
scanf("%d",&arr[i]); {
} printf("%d ", ptr[i]);
return arr; }
}
Using Structure
The structure is a user-defined data type that can contain a
collection of items of different types. Now, we will create a
program that returns an array by using structure.
#include <stdio.h> return y;
#include<malloc.h> }
struct array int main()
{ {
int arr[8]; struct array x=getarray();
}; printf("Elements that you have entered are :
struct array getarray() ");
{ for(int i=0;[Link][i]!='\0';i++)
struct array y; {
printf("Enter the elements in an array : "); printf("%d ", [Link][i]);
for(int i=0;i<8;i++) }
{ return 0;
scanf("%d",&[Link][i]); }
}
Passing Array to Function in C
• In C, there are various general problems which requires passing
more than one variable of the same type to a function. For example,
consider a function which sorts the 10 elements in ascending order.
Such a function requires 10 numbers to be passed as the actual
parameters from the main function. Here, instead of declaring 10
different numbers and then passing into the function, we can
declare and initialize an array and pass that into the function. This
will resolve all the complexity since the function will now work for
any number of values.
• As we know that the array_name contains the address of the first
element. Here, we must notice that we need to pass only the name
of the array in the function which is intended to accept an array. The
array defined as the formal parameter will automatically refer to the
array specified by the array name defined as an actual parameter.
syntax to pass an array to the function.
functionname(arrayname);//passing array
Methods to declare a function that receives an array as an argument
There are 3 ways to declare the function which is intended to receive an array as an
argument.
First way:
return_type function(type arrayname[])
Declaring blank subscript notation [] is the widely used technique.
Second way:
return_type function(type arrayname[SIZE])
Optionally, we can define size in subscript notation [].
Third way:
return_type function(type *arrayname)
You can also use the concept of a pointer. In pointer chapter, we will learn about it.
passing an array to function
#include<stdio.h> int main(){
int minarray(int arr[],int size){ int i=0,min=0;
int min=arr[0]; int numbers[]={4,5,7,3,8,9};//
int i=0; declaration of array
for(i=1;i<size;i++){
if(min>arr[i]){ min=minarray(numbers,6);//
passing array with size
min=arr[i];
printf("minimum number is %d \
} n",min);
}//end of for return 0;
return min; }
}//end of function