Array is a collection of data elements, all of same data type, accessed using a common name. Array elements are placed in contiguous memory location. Array is one type of data structure that can store a fixed-size sequential collection of items of the same type. An array is a variable that can store multiple values. Array is the collection of homogeneous data elements.
To declare array in C, a programmer specifies the data type of items, array name and numbers of
items
required by an array as follows -
type arrayname[arraysize];
type arrayname[i][j];
In C programming language, there is two type of array-
// Print the elements stored in the array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5]={1,2,3,4,5};
clrscr();
// printing elements of an array
for(int i = 0; i < 5; i++)
{
printf("%d\n", a[i]);
}
getch();
}
1 2 3 4 5
// Print the elements stored in the array
#include<stdio.h>
#include<conio.h>
void main()
{
int a[5];
clrscr();
printf("Enter 5 elements in the array/n");
scanf("&d", &a[i]);
// taking input and storing it in an array
for( i = 0; i < 5; i++) {
scanf("%d", &a[i]);
}
printf("Displaying array elements/n");
// printing elements of an array
for(int i = 0; i < 5; i++)
{
printf("%d\n", a[i]);
}
getch();
}
Enter 5 elements in the array 10 20 30 40 50 Displaying array elements 10 20 30 40 50
//Print sum of array elements
#include<stdio.h>
int main()
{
int array[5];
int sum, i;
sum = 0;
printf("Enter values in 1-D array/n")
for(i = 0; i < 6; i++);
{
scanf("%d",array[i]);
}
for(i = 0; i < 6; i++)
{
sum = sum + array[i];
}
printf("Sum of array is %d", sum);
return 0;
}
Enter values in 1-D array 1 2 3 4 5 Sum of array is 15
//program for compile time array initialization
#include<stdio.h>
void main()
{
int a[2][2]={{1,2},{3,4}};
int i,j;
printf(“Array elements are\n”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf(“%d\n”,a[i][j]);
}
}
return 0;
}
Array elements are 1 2 3 4
// Print the elements stored in the array
#include<stdio.h>
void main()
{
int a[2][2];
int i,j;
printf(“Enter the array elements \n”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
scanf(“%d”,&a[i][j]);
}
}
printf(“Array elements are \n”);
for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
printf(“%d\n”,a[i][j]);
}
}
return 0;
}
Enter the array elements 5 6 7 8 Array elements are 5 6 7 8