Array
Array is collection of homogeneous data items. Array provides us a way to store large number of variables which is of same data type under single name. for example suppose you want to store 10 values. for that one way is declaring 10 variables like number 1, number 2, number 2….number 10 in which each variable will store a single value. But this process will be very complex and inefficient if the number of values you want to store is very large.
To avoid this C provides us a very simple way of storing all the values of same data types under a single variable, and that variable which store these values is called array.
Array is of two types;
1) single dimensional array
2) multi dimensional array
To understand basics of array we will first concentrate on single dimensional array.
–>Declaration of single dimensional array:-
following is the syntax of declaring an array
data_type array_name[size_of_array];
data_type:- it is the type of elements you want to store in array.
array_name:- it is the name of array .
size_of_array:- it is the numbers of elements you want to store in array;
example:
int store[10];
above statement declare an array store which will store 10 variable of integer data type.
we can also initialize array while declaration by providing the values which we want to store at the time of declaration. for example:
int store[5]={1,2,3,4,5};
above statement declare and initialize an array store which store values from 1 to 5.
Memory representation of an array:-
Sequential memory is allocated for array and all the members are stored in a sequential way.
int store[10];
above declaration will allocate memory for storing 10 variable of integer data type.
accessing array member
array member is accessed by indexing the variable name.which is done by placing the index of the element with in square bracket after the name of array. below is the syntax
array_name[index];
array_name:- is the name of an array.
index:- index specify the position of variable which you want to access . generally in array index starts by value 0.
for example:- if we want to access the 7th member of array store then we can do this by below statement
int store[10];
int num=store[6];
above statement will store the value of 7th member of array store in variable num.
example of single dimensional array in c:-
Program to store 5 values and find total sum of all the values:
include<stdio.h>
int main()
{
int store[10]; //array to store 10 elements
int sum=0; //variable to store the sum of all the numbers.
printf(“enter the values one by one”);
for(int i=0;i<5;i++)
{
printf(“enter value%d:”);
scanf(“%d”,store[i]);
sum=sum+store[i];
}
printf(“sum of all the values is = %d”,sum);
after compiling and excuting this programm we will get below output.
enter value: 5
enter value1: 2
enter value2: 1
enter value3: 10
enter value4: 4
sum of all the values is =22
For understanding the multidimensional array please visit the next chapter.