Arrays
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.
What are Arrays?
An array is a sequence of data item of homogeneous value(same type).
Memory Representation of arrays.
int marks[5] = {51,62,43,74,55};
Here an array marks of 5 elements is created. Figure shows its memory representation.
Array Declaration
To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows.
type arrayName[array size];
This is called a single-dimensional array. The arraySize must be an integer constant greater than zero and type can be any valid C data type. For example, to declare a 10-element array called balance of type double, use this statement:
double balance[10];
Array Initialization
int num[6] = {4,5,3,6,34,56};
int num[] = {4,5,3,6,34,56};
float press[] = { 12.4,5.6,7.5,3.3,2};
Accessing Array Elements
int arr[5] = {12,5,6,3,4};
int x= arr[3];
int y= arr[4];
int z= arr[0]+arr[2];
printf("%d %d %d",x,y,z);
output: 3 4 18
printf("%d", arr[5]);
output: Error - Array Index Out of bound
Basic Array Program
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j;
/* initialize elements of array n to 0 */
for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100; /* set element at location i to i + 100 */
}
/* output each array element's value */
for (j = 0; j < 10; j++ )
{
printf("Element[%d] = %d\n", j, n[j] );
}
return 0;
}
Output:
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109
Another Example
1. C Program to Calculate Sum & Average of an Array
2. C Program to Find the Largest Numbers in a given Array.
3. C Program to Find the Largest Two Numbers in a given Array.
4. C Program to Put Even & Odd Elements of an Array in 2 Separate Arrays.
5. C Program to Find the Second Largest & Smallest Elements in an Array
Some Practice Problems...
For more problems refer: http://www.sanfoundry.com/c-programming-examples-arrays/
Arrays
By Atul Mishra
Arrays
- 1,359