Programming in c
array
An array is a collection of elements of same data
type stored in contiguous memory locations and
accessed using single name with an index.
Why arrays?
Stores multiple values using one variable
Easy data handing
Faster access using index
Used in searching, sorting, matrices, etc.
Declaration of Array
data_type array_name[size];
int a[5];
Initialization of array
1. At declaration time
int a[5]= {10, 20, 30, 40,50};
2. Without size
int a[]= {1, 2, 3, 4};
3. Partial initialization
int a[5] = {1, 2};
Accessing array elements
Array elements are accessed using the array
name and index number.
Index starts from 0
Accessing elements using loop
Example: Output:
#include <stdio.h>
int main(){ 12345
int a[5] = { 1, 2, 3, 4, 5};
int i;
for(i = 0; i<5; i++){
printf(“%d”, a[i]);}
return 0;}
Accessing elements using scanf
#incude <stdio.h>
int main(){
int a[3], I;
for(i = 0; i < 3; i++){
scanf(“%d”, &a[i]);
}
for(i = 0; i < 3; i++){
printf(“%d”, a[i]);
}
return 0;
}
Types of Array
1. One- dimensional Array(1D Array)
A linear list of elements stored in continuous
memory.
Used for storing marks, salaries , list of
numbers.
int a[5] = {4, 8, 12, 16, 20};
2. Two- dimensional array(2d)
An array of arrays(rows and columns) matrix
form
Declaration
int a[2][3];
Initialization:
int a[2][3] = {{1,2,3} , {4,5,6});
Example: Matrix addition
#include <stdio.h>
int main(){
int a[2][2], b[2][2], sum[2][2];
int i, j;
Printf(“Enter elements of matixA:\n”);
for(i =0 ; i< 2; i++){
for (j = 0; j<2; j++){
scanf (“%d”, &a[i][j]);}}
Printf(“Enter elements of matixB:\n”);
for(i =0 ; i< 2; i++){
for (j = 0; j<2; j++){
scanf (“%d”, &b[i][j]);}}
for(i =0 ; i< 2; i++){
for (j = 0; j<2; j++){
Sum[i][j]= a[i][j] + b[i][j];}}
Printf(“sum of matices:\n”);
for(i =0 ; i< 2; i++){
for (j = 0; j<2; j++){
scanf (“%d”, sum[i][j]);}
printf(“\n”);
} return 0;}