Table of Contents
show
An array is a sequence of data item of homogeneous value (same type). All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
Arrays are of two types
- One-dimensional arrays
- Multidimensional arrays
Declaration of one-dimensional array
data_type array_name[array_size];
Example
int age[5];
Here, the name of array is age. The size of array is 5,i.e., there are 5 items(elements) of arrayage. All element in an array are of the same type (int, in this case)
Initialization of one-dimensional array
Arrays can be initialized at declaration time as:
data_type arr_name [arr_size]={value1, value2, value3,….};
Example,
int age[5]={2,4,34,3,4};
Accessing Array elements in one-dimensional array
arr_name[index];
Example
age[0]; /*0 is accessed*/
age[1]; /*1 is accessed*/
age[2]; /*2 is accessed*/
Program 1: To read elements in array and to print the array elements
#include<stdio.h>
int main()
{
int a[5],i;
printf("Enter array elements\n");
// loop to get array elements
for(i=0;i<5;i++)
{
scanf("%d",&a[i]);
}
// loop to print array elements
printf("\n The elements are:\n");
for(i=0;i<5;i++)
{
printf("%d\t",a[i]);
}
return 0;
}
Output
Enter array elements
34 45 56 78 90
The elements are:
34 45 56 78 90
Program 2: To add array elements (or) sum of marks
#include<stdio.h>
int main()
{
int m[100],i,n,sum = 0;
printf("Enter size of array\n");
scanf("%d",&n);
printf("Enter array elements\n");
// loop to get array elements
for(i=0;i<n;i++)
{
scanf("%d",&m[i]);
}
// loop to add array elements
printf("\n The elements are:\n");
for(i=0;i<n;i++)
{
sum = sum +m[i];
}
printf("Result = %d",sum);
return 0;
}
Output
Enter size of array
5
Enter array elements
50 25 25 50 100
The elements are:
Result = 250
Views: 0