07 Arrays
07 Arrays
07 Arrays
This will reserve 100 contiguous memory locations for storing the
students’ marks.
Graphically, this can be depicted as in the following figure.
Eg: if we declare variable, memory will be allotted randomly
int n1, n2, n3, n4, n5, n6, n7
Declaring an Array:- Like any other variable, array must be
declared before they are used.
Syntax:
datatype array_name[size] = {list of values};
Example:
int marks[4] = {67, 82, 56, 77}; //fixed length//integer array
initialization
float area[2] = {23.4, 6.8}; //float array initialization
int marks[4] = {67, 82, 56, 77, 59}; //compile time error
int arr[] = {2, 3, 4}; variable lenth//compile time array
initialization.
Run time array initialization:
It is done using scanf() function. This approach is usually
used for initializing large array, or to initialize array with
user specified values.
Eg:
For(i=0;i<n-1;i++)
{
scanf(“%d”,&arr[i]); //run time array initialization.
}
Example: One dimensional array
main()
{
int sub[5], i, total=0;
printf(“enter 5 numbers\n”);
for(i=0;i<5;i++)
{
scanf(“%d”,&sub[i]);
total=total + sub[i];
}
for(i=0;i<5;i++)
{
printf(“%d\n”,sub[i]);
}
printf(“total is %d\n”,total);
}
Linear search
Syntax
int a[3][4];
This array can also be declared and initialized together. Such as
Ex:
int arr[][3] = {……….. {0,0,0}, {1,1,1} };
scanf(“%d”,&arr[i][j]);
Example: Two dimensional array
main()
{
int b[2][3];
int i, j;
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
scanf(“%d”,&b[i][j]);
}
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
printf(“%d\t”,b[i][j]);
}
printf(“\n”);
}}