arrays:
DEF: Array is a collection of similar type of
elements, that can share common name.
Syntax to declare array:
data_type array_name
dimension
[]
à Single dimension
array
[][]
à Two dimensional
array
[][][] Ã
three dimensional array
Arrays are of two types:
1) 1. Single dimensional
arrays à it is only one dimension
2) 2. Multi Dimensional
arrays à it contains more than one
dimension
Working with single dimension arrays:
Syntax
:
data_type array_name [n];
nÃ
no of elements.
Eg:
int
a[5];
int b[]; Ã Invalid
memory
map for the above
|
|
|
|
|
Size of array = no.of elements *
sizeof(data_type);
In the above example
Sizeof of array =
5 * 2 = 10 bytes
Memory allocation for the arrays is a
sequential manner.
Accessing array elements :
Assigning values to array elements :
a[5]= 60; Ã invalid, it raises memory
exception.
int
a[5]={1,2,3,4,5}; Ã Valid
int a[
]={1,2,3,4,5}; Ã Valid
int
a[5]={1,2,3,4}; Ã Valid, fifth value may be garbage
int
a[5]={1,2,3,4,5,6}; Ã Invalid, since no of elements are
more than size of
the array.
Reading array elements from key board:
for(i=0; i<n ; i++)
{
scanf(“%d”,&a[i]);
}
Displaying array elements:
for(i=0; i<n ; i++)
{
printf(“%d”,a[i]);
}
Program to read and display array elements:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int a[50];
int n,i;
printf("\nEnter how many elements");
scanf("%d",&n);
if(n<1
|| n>50)
{
printf("\n Invalid no of
elements");
exit(0);
}
printf("\nEnter
the elements");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nElements
are ");
for(i=0;i<n;i++)
{
printf("%d ",a[i]);
}
getch();
}
0 Comments