Arrays
Definition
An Array is a collection of elements of the same data type.
Declaration
int ar[10];
char ch[10];
Initialisation
Initialisation refers to giving an initial value to a variable.
int ar[5] = { 10, 20, 30, 40, 50};
Referencing
Every element in an array can be referenced by its index. Index numbers range from 0 to ( length of array - 1 ).
Following is an example of indexes of the array declared above.
ELEMENTS | 10 | 20 | 30 | 40 | 50 |
---|---|---|---|---|---|
INDEX | 0 | 1 | 2 | 3 | 4 |
ar[3]
--> 40
ar[0]
--> 10
Looping
To reference each element of the array we use loops.
Input
#include <stdio.h>
int main()
{
int ar[5];
for (int i = 0; i < 5; i++)
{
scanf("%d", &ar[i]);
}
return 0;
}
Output
#include <stdio.h>
int main()
{
int ar[5];
// INPUT
for (int i = 0; i < 5; i++)
{
scanf("%d", &ar[i]);
}
// OUTPUT
for (int i = 0; i < 5; i++)
{
printf("%d", ar[i]);
}
return 0;
}
Find Arrays programs here:
https://github.com/TejasBhovad/c-programs/arrays