C Array

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

Arrays

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.
1. data_type array_name[array_size];

Now, let us see the example to declare the array.

1. 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.

1. marks[0]=80;//initialization of array
2. marks[1]=60;
3. marks[2]=70;
4. marks[3]=85;
5. marks[4]=75;

C array example

1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5];//declaration of array
5. marks[0]=80;//initialization of array
6. marks[1]=60;
7. marks[2]=70;
8. marks[3]=85;
9. marks[4]=75;
10. //traversal of array
11. for(i=0;i<5;i++){
12. printf("%d \n",marks[i]);
13. }//end of for loop
14. return 0;
15. }
C Array: Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.

1. 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.

1. int marks[]={20,30,40,50,60};

Let's see the C program to declare and initialize the array in C.

1. #include<stdio.h>
2. int main(){
3. int i=0;
4. int marks[5]={20,30,40,50,60};//declaration and initialization of array
5. //traversal of array
6. for(i=0;i<5;i++){
7. printf("%d \n",marks[i]);
8. }
9. return 0;
10. }

C Array Example: Sorting an array


In the following program, we are using bubble sort method to sort the array in ascending order.

1. #include<stdio.h>
2. void main ()
3. {
4. int i, j,temp;
5. int a[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. for(i = 0; i<10; i++)
7. {
8. for(j = i+1; j<10; j++)
9. {
10. if(a[j] > a[i])
11. {
12. temp = a[i];
13. a[i] = a[j];
14. a[j] = temp;
15. }
16. }
17. }
18. printf("Printing Sorted Element List ...\n");
19. for(i = 0; i<10; i++)
20. {
21. printf("%d\n",a[i]);
22. }
23. }

Program to print the largest and second largest element of


the array.
1. #include<stdio.h>
2. void main ()
3. {
4. int arr[100],i,n,largest,sec_largest;
5. printf("Enter the size of the array?");
6. scanf("%d",&n);
7. printf("Enter the elements of the array?");
8. for(i = 0; i<n; i++)
9. {
10. scanf("%d",&arr[i]);
11. }
12. largest = arr[0];
13. sec_largest = arr[1];
14. for(i=0;i<n;i++)
15. {
16. if(arr[i]>largest)
17. {
18. sec_largest = largest;
19. largest = arr[i];
20. }
21. else if (arr[i]>sec_largest && arr[i]!=largest)
22. {
23. sec_largest=arr[i];
24. }
25. }
26. printf("largest = %d, second largest = %d",largest,sec_largest);
27.
28. }

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.

1. data_type array_name[rows][columns];

Consider the following example.

1. 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.

Two-dimensional array example in C

1. #include<stdio.h>
2. int main(){
3. int i=0,j=0;
4. int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
5. //traversing 2D array
6. for(i=0;i<4;i++){
7. for(j=0;j<3;j++){
8. printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
9. }//end of j
10. }//end of i
11. return 0;
12. }

C 2D array example: Storing elements in a matrix and printing it.

1. #include <stdio.h>
2. void main ()
3. {
4. int arr[3][3],i,j;
5. for (i=0;i<3;i++)
6. {
7. for (j=0;j<3;j++)
8. {
9. printf("Enter a[%d][%d]: ",i,j);
10. scanf("%d",&arr[i][j]);
11. }
12. }
13. printf("\n printing the elements ....\n");
14. for(i=0;i<3;i++)
15. {
16. printf("\n");
17. for (j=0;j<3;j++)
18. {
19. printf("%d\t",arr[i][j]);
20. }
21. }
22. }

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 a function.

Passing array to a function

1. #include <stdio.h>
2. void getarray(int arr[]) //declare and define the funtion
3. {
4. printf("Elements of array are : ");
5. for(int i=0;i<5;i++)
6. {
7. printf("%d ", arr[i]);
8. }
9. } //end the function
10. int main()
11. {
12. int arr[5]={45,67,34,78,90}; //declare and initialize the array
13. getarray(arr); //call the function
14. return 0;
15. }

In the above program, we have first created the array arr[] and then we pass this array to the
function getarray(). The getarray() function prints all the elements of the array arr[].

Passing array to a function as a pointer

Now, we will see how to pass an array to a function as a pointer.

1. #include <stdio.h>
2. void printarray(char *arr)
3. {
4. printf("Elements of array are : ");
5. for(int i=0;i<5;i++)
6. {
7. printf("%c ", arr[i]);
8. }
9. }
10. int main()
11. {
12. char arr[5]={'A','B','C','D','E'};
13. printarray(arr);
14. return 0;
15. }

In the above code, we have passed the array to the function as a pointer. The function
printarray() prints the elements of an array.

How to return an array from a function

Returning pointer pointing to the array

1. #include <stdio.h>
2. int *getarray()
3. {
4. int arr[5];
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &arr[i]);
9. }
10. return arr;
11. }
12. int main()
13. {
14. int *n;
15. n=getarray();
16. printf("\nElements of array are :");
17. for(int i=0;i<5;i++)
18. {
19. printf("%d", n[i]);
20. }
21. return 0;
22. }

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.

1. #include <stdio.h>
2. int *getarray(int *a)
3. {
4.
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<5;i++)
7. {
8. scanf("%d", &a[i]);
9. }
10. return a;
11. }
12. int main()
13. {
14. int *n;
15. int a[5];
16. n=getarray(a);
17. printf("\nElements of array are :");
18. for(int i=0;i<5;i++)
19. {
20. printf("%d", n[i]);
21. }
22. return 0;
23. }

Returning array using malloc() function.

1. #include <stdio.h>
2. #include<malloc.h>
3. int *getarray()
4. {
5. int size;
6. printf("Enter the size of the array : ");
7. scanf("%d",&size);
8. int *p= malloc(sizeof(size));
9. printf("\nEnter the elements in an array");
10. for(int i=0;i<size;i++)
11. {
12. scanf("%d",&p[i]);
13. }
14. return p;
15. }
16. int main()
17. {
18. int *ptr;
19. ptr=getarray();
20. int length=sizeof(*ptr);
21. printf("Elements that you have entered are : ");
22. for(int i=0;ptr[i]!='\0';i++)
23. {
24. printf("%d ", ptr[i]);
25. }
26. return 0;
27. }

Using Static Variable

1. #include <stdio.h>
2. int *getarray()
3. {
4. static int arr[7];
5. printf("Enter the elements in an array : ");
6. for(int i=0;i<7;i++)
7. {
8. scanf("%d",&arr[i]);
9. }
10. return arr;
11.
12. }
13. int main()
14. {
15. int *ptr;
16. ptr=getarray();
17. printf("\nElements that you have entered are :");
18. for(int i=0;i<7;i++)
19. {
20. printf("%d ", ptr[i]);
21. }
22. }

In the above code, we have created the variable arr[] as static in getarray() function, which is
available throughout the program. Therefore, the function getarray() returns the actual memory
location of the variable '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.

1. #include <stdio.h>
2. #include<malloc.h>
3. struct array
4. {
5. int arr[8];
6. };
7. struct array getarray()
8. {
9. struct array y;
10. printf("Enter the elements in an array : ");
11. for(int i=0;i<8;i++)
12. {
13. scanf("%d",&y.arr[i]);
14. }
15. return y;
16. }
17. int main()
18. {
19. struct array x=getarray();
20. printf("Elements that you have entered are :");
21. for(int i=0;x.arr[i]!='\0';i++)
22. {
23. printf("%d ", x.arr[i]);
24. }
25. return 0;
26. }

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.

Consider the following syntax to pass an array to the function.

1. 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:
1. return_type function(type arrayname[])

Declaring blank subscript notation [] is the widely used technique.

Second way:

1. return_type function(type arrayname[SIZE])

Optionally, we can define size in subscript notation [].

Third way:

1. return_type function(type *arrayname)

You can also use the concept of a pointer. In pointer chapter, we will learn about it.

C language passing an array to function example

1. #include<stdio.h>
2. int minarray(int arr[],int size){
3. int min=arr[0];
4. int i=0;
5. for(i=1;i<size;i++){
6. if(min>arr[i]){
7. min=arr[i];
8. }
9. }//end of for
10. return min;
11. }//end of function
12.
13. int main(){
14. int i=0,min=0;
15. int numbers[]={4,5,7,3,8,9};//declaration of array
16.
17. min=minarray(numbers,6);//passing array with size
18. printf("minimum number is %d \n",min);
19. return 0;
20. }

Output

minimum number is 3

C function to sort the array


1. #include<stdio.h>
2. void Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. Bubble_Sort(arr);
7. }
8. void Bubble_Sort(int a[]) //array a[] points to arr.
9. {
10. int i, j,temp;
11. for(i = 0; i<10; i++)
12. {
13. for(j = i+1; j<10; j++)
14. {
15. if(a[j] < a[i])
16. {
17. temp = a[i];
18. a[i] = a[j];
19. a[j] = temp;
20. }
21. }
22. }
23. printf("Printing Sorted Element List ...\n");
24. for(i = 0; i<10; i++)
25. {
26. printf("%d\n",a[i]);
27. }
28. }

array from the function


As we know that, a function can not return more than one value. However, if we try to write the
return statement as return a, b, c; to return three values (a,b,c), the function will return the last
mentioned value which is c in our case. In some problems, we may need to return multiple
values from a function. In such cases, an array is returned from the function.

Returning an array is similar to passing the array into the function. The name of the array is
returned from the function. To make a function returning an array, the following syntax is used.

1. int * Function_name() {
2. //some statements;
3. return array_type;
4. }

To store the array returned from the function, we can define a pointer which points to that array.
We can traverse the array by increasing that pointer since pointer initially points to the base
address of the array. Consider the following example that contains a function returning the sorted
array.

1. #include<stdio.h>
2. int* Bubble_Sort(int[]);
3. void main ()
4. {
5. int arr[10] = { 10, 9, 7, 101, 23, 44, 12, 78, 34, 23};
6. int *p = Bubble_Sort(arr), i;
7. printf("printing sorted elements ...\n");
8. for(i=0;i<10;i++)
9. {
10. printf("%d\n",*(p+i));
11. }
12. }
13. int* Bubble_Sort(int a[]) //array a[] points to arr.
14. {
15. int i, j,temp;
16. for(i = 0; i<10; i++)
17. {
18. for(j = i+1; j<10; j++)
19. {
20. if(a[j] < a[i])
21. {
22. temp = a[i];
23. a[i] = a[j];
24. a[j] = temp;
25. }
26. }
27. }
28. return a;
29. }

You might also like