C Arrays - Declare, Initialize and Access Elements With Examples
C Arrays - Declare, Initialize and Access Elements With Examples
In this article, you will learn to work with arrays. You will learn to declare, initialize and,
access array elements with the help of examples.
An array is a collection of data that holds fixed number of values of same type. For example: if you
want to store marks of 100 students, you can create an array for it.
float marks[100];
The size and type of arrays cannot be changed after its declaration.
1. One-dimensional arrays
2. Multidimensional arrays (will be discussed in next chapter)
float mark[5];
Here, we declared an array, mark , of floating-point type and size 5. Meaning, it can hold 5 floating-
point values.
Suppose you declared an array mark as above. The first element is mark[0] , second element
is mark[1] and so on.
Here,
mark[0] is equal to 19
mark[1] is equal to 10
mark[2] is equal to 8
mark[3] is equal to 17
mark[4] is equal to 9
Example: C Arrays
// Program to find the average of n (n < 10) numbers using arrays
#include <stdio.h>
int main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
return 0;
}
Output
Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
int testArray[10];
If you try to access array elements outside of its bound, let's say testArray[12] , the compiler may
not show any error. However, this may cause unexpected output (undefined behavior).