What is arrays?
The array are defined as the collection of homogenous data type. It is a collection of similar data type or collection of same type of data type store in a continuous memory location. Each element is unique and located in a separate memory location.
To obtain the length of the array the following formula is applied on the index set to obtain the length of the array.
Length = upper bound - lower bound +1
Upper bond = largest index number
Lower bond = smallest index number
Initialization of C Array
The easiest way to initialize an array by using there index value of each element.
- array[0]=10;//initialization of array
- array[1]=20;
- array[2]=30;
- array[3]=40;
- array[4]=50;
Let's take an example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i=0;
int array[5];//declaration of array
array[0]=10;//initialization of array
array[1]=20;
array[2]=30;
array[3]=40;
array[4]=50;
for(i=0;i<5;i++)
{
printf("%d \n",array[i]);
}
getch( );
}
C Array: Declaration with Initialization
You can declare the values with size or without size.
int array[5]={10,20,30,40,50};
int array[ ]={10,20,30,40,50};
Now, let's understand with a program how to search an element within an array.
#include<stdio.h>
#include<conio.h>
void main()
{
int array[20], search, j, n;
clrscr();
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d integer(s)\n", n);
for (j = 0; j < n; j++)
scanf("%d", &array[j]);
printf("Enter a number to search\n");
scanf("%d", &search);
for (j = 0; j < n; j++)
{
if (array[j] == search)
{
printf("%d is present at location %d.\n", search, j+1);
break;
}
}
if (j == n)
printf("%d isn't present in the array.\n", search);
getch( );
}
0 Comments
Have any query? Want any type of module?
Please comment it down and let me know.