In this tutorial, you will learn about c programming arrays.
An array is a collection of same types of data items that are placed in the contiguous memory location on computers memory.
When we need to handle the multiple data of similar types arrays are used.
For example, we need 10 unique variables for 10 data items of integer type which make program bulky and tedious but with an array, we can create a single pack of 10 integer data items.
For example:
int num[10]; //num is a variable that will hold 10 integer data items
Basically, there are two types of arrays:
data_type variable_name[array_size]; //declaring an one dimensional
In above syntax, the “data_type” as the name suggests defines the types of data items that the array will be holding,“variable_name” defines the unique name of an array and the “array_size” defines the number of elements contained in the array.
Once the array is declared it must be initialized otherwise it will contain a garbage value.
data_type variable_name[size] = { list }; //initializing an array
The values in the list are separated by commas.
[adsense1]
For example:
int a[]={1,2,3,4,5};
This declaration will create an array like this:
Or if we insert size of an array then the number of elements must not exceed the size.
int a[5]={0}; //this will assign 0 to all 5 elements
To initialize character arrays
char a[]={'a','b','c','d'};
Normally, when we declare multiple variables they occupy memory and are randomly placed in computers memory heap, however, when we declare an array of multiple data items these items occupy the continuous memory locations in computers memory heap.
For example, take an integral constant which takes 4 bytes of computers memory.
Now, if the first element of an array a[0]
is stored at memory location 0x12 (say) then the second element a[1]
of an array will be stored at the memory location adjacent to it which is 0x16 as integer occupies 4 bytes of memory.
#include <stdio.h> #define SIZE 5 //sizi of array int main() { int a[SIZE] = {1,2,3,4,5}; //array a has SIZE elements .... }
Here, #define
preprocessor directive defines a symbolic constant SIZE whose value is 5.
#define
and #include
because preprocessor directive are not C statements.
#include <stdio.h>
#include <stdio.h>
int main ()
{
int i, a[5] ,sum = 0; //a[5] is array that can hold 5 integer data items
for(i=0;i<5;i++) //loop to be repeated 5 times
{
printf("enter the number "<< i+1<<":");
scanf("%d", &a[i];
sum = sum + a[i];
}
printf("sum = %d",sum);
return 0;
} //end of program
Output
enter the number 1 : 1 enter the number 2 : 2 enter the number 3 : 3 enter the number 4 : 4 enter the number 5 : 5 sum = 15
Summary