Programs to learn about array .
Array : An array is defined as finite ordered collection of homogenous data, stored in contiguous memory locations.
- finite means data range must be defined.
- ordered means data must be stored in continuous memory addresses.
- homogenous means data must be of similar data type.
Advantages of Array :
- Less code to the access the data.
- By using the for loop, we can retrieve the elements of an array easily.
- To sort the elements of the array, we need a few lines of code only.
- We can access any element randomly using the array.
Disadvantages of Array :
- We must know in advance that how many elements are to be stored in array.
- Array is static structure. It means that array is of fixed size. The memory which is allocated to array can not be increased or reduced.
- Since array is of fixed size, if we allocate more memory than requirement then the memory space will be wasted. And if we allocate less memory than requirement, then it will create problem.
- The elements of array are stored in consecutive memory locations. So insertions and deletions are very difficult and time consuming.
Declaration of Array :
Syntax : data_type array_name[array_size];
Example : int A[5];
Initialization of an Array :
Syntax : data-type array-name[size] = { list of values };
Example : int A[4]={ 67, 87, 56, 77 };
Program :
#include<stdio.h> #include<conio.h> void main () { int i, j,temp; int a[10] = { 1, 9, 7, 10, 2, 44, 11, 99, 20, 24}; for(i = 0; i<10; i++) { for(j = i+1; j<10; j++) { if(a[j] > a[i]) { temp = a[i]; a[i] = a[j]; a[j] = temp; } } } printf("Sorted List ...\n"); for(i = 0; i<10; i++) { printf("%d ",a[i]); } } |
---|
Output :
Sorted List ...
99 44 24 20 11 10 9 7 2 1
Two-Dimension Array :
Declaration of two dimensional Array :
Syntax : data_type array_name[rows][columns];
Example : int A[4][3];
Initialisation of two dimensional Array :
Syntax : data-type array-name[no of rows][no of columns] = { list of values };
Example : int A[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Program :
#include<stdio.h> #include<conio.h> void main() { int m, n, c, d, first[10][10], second[10][10], sum[10][10]; printf("Enter the number of rows and columns of matrix\n"); scanf("%d%d", &m, &n); printf("Enter the elements of first matrix\n"); for (c = 0; c < m; c++) for (d = 0; d < n; d++) scanf("%d", &first[c][d]); printf("Enter the elements of second matrix\n"); for (c = 0; c < m; c++) for (d = 0 ; d < n; d++) scanf("%d", &second[c][d]); printf("Sum of entered matrices:-\n"); for (c = 0; c < m; c++) { for (d = 0 ; d < n; d++) { sum[c][d] = first[c][d] + second[c][d]; printf("%d\t", sum[c][d]); } printf("\n"); } } |
---|
Output :
Enter the number of rows and columns of matrix
3 4
Enter the elements of first matrix
1 2 3 4
1 1 1 1
2 3 4 1
Enter the elements of second matrix
0 0 0 0
1 0 0 0
3 2 1 0
Sum of entered matrices:-
1 2 3 4
2 1 1 1
5 5 5 1
For more RTU/BTU II Sem Computer Programming Lab Experiments CLICK HERE