In C Programming, an array can be defined as number of memory locations, each of which can store the same data type and which can be referenced through the same variable name.
Arrays can be of two types i.e. One Dimensional Array (such as lists) and Multidimensional Arrays (such as tables or matrices) wikipedia.
An array is defined in a very straightforward syntax in C as: int age [5];
An array is a collective name given to a group of similar quantities or values. These similar quantities could be percentage marks of 100 students, number of chairs in home, or salaries of 300 employees or ages of 25 students. Thus an array is a collection of similar elements. These similar elements could be all integers or all floats or all characters etc.
Usually, the array of characters is called a “string”, where as an array of integers or floats is called simply an array. All elements of any given array must be of the same type i.e. we can’t have an array of 10 numbers, of which 5 are int and 5 are float.
Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.
Table of Contents
- How to Declare an Array in C?
- How to View and Access Array Elements?
- How to Initialize Arrays in C?
- Initializing and Printing Arrays using for Loops
- How to Determine the Size of Array in C?
- How to Perform Read/Write Operations on Arrays?
- How to Copy one Array into Another?
- Multidimensional Arrays in C
How to Declare an Array in C?
Arrays should be declared before they can be used in the C program. Standard array declaration is as
data_type variable_name[sire_of_array];
Here data_type specifies the variable type of the element which is going to be stored in the array. In C programming language we can declare the array of any basic standard types. For example
double height[10]; float width[20]; int min[9]; char name[5];
Here we declared array height of double data type and size 10, array width of float data type and size 20, array min of int data type and size 9, array name of char data type and size 5.
How to View and Access Array Elements?
In C programming, array elements are accessed with indices which starts at position 0. The elements of the array occupy adjacent locations in memory. C treats the name of the array as if it were a pointer to the first element. This is important in understanding how to do arithmetic with arrays. Any item in the array can be accessed through its index, and it can be accessed any where from with in the program. So
m=height[0];
Here, variable m will have the value of first item of array height.
The following C program will declare an array of five integers and prints all the elements of the array.
#include <stdio.h>
int main()
{
int height [5] = {1,2,3,4,5};
/* To print all the elements of the array
for (int i=0; i < 5; i++){
printf("%d", height[i]);
}
return 0;
}
How to Initialize Arrays in C?
In C, arrays can be initialized in two ways 1) initializing while declaration 2) initializing after declamation. The initializing values are enclosed within the curly braces in the declaration.
Here is an example which declares and initializes an array of five elements of type int. Array can also be initialized after declaration. Look at the following C code which demonstrate the declaration and initialization of an array.
Initializing Array While Declaration
You can initialize an array during its declaration by providing a list of initial values enclosed in curly braces {}
. Here’s an example:
#include <stdio.h>
int main() {
// Initializing an array of integers
int numbers[5] = {1, 2, 3, 4, 5};
// Initializing an array of characters (string)
char characters[] = {'H', 'e', 'l', 'l', 'o'};
// Initializing an array of floating-point numbers
float floats[] = {3.14, 2.718, 1.618};
// Printing the initialized arrays
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
for (int i = 0; i < 5; i++) {
printf("%c ", characters[i]);
}
printf("\n");
for (int i = 0; i < 3; i++) {
printf("%.3f ", floats[i]);
}
printf("\n");
return 0;
}
Initializing Array After Declaration
int weight[5]; weight[0]=14; weight[1]=13; weight[2]=15; weight[3]=16; weight[4]=20;
Initializing and Printing Arrays using for Loops
Here is a C program that will demonstrate how we can use for loop to initialize and print the elements of an array.
#include <stdio.h>
void oneWay(void);
void anotherWay(void);
int main(void) {
printf("\noneWay:\n");
oneWay();
printf("\nantherWay:\n");
anotherWay();
}
/*Array initialized with aggregate */void oneWay(void) {
int vect[10] = {1,2,3,4,5,6,7,8,9,0};
int i;
for (i=0; i<10; i++){
printf("i = %2d vect[i] = %2d\n", i, vect[i]);
}
}
/*Array initialized with loop */void anotherWay(void) {
int vect[10];
int i;
for (i=0; i<10; i++)
vect[i] = i+1;
for (i=0; i<10; i++)
printf("i = %2d vect[i] = %2d\n", i, vect[i]);
}
The output of the above C program is as below:
oneWay: i = 0 vect[i] = 1 i = 1 vect[i] = 2 i = 2 vect[i] = 3 i = 3 vect[i] = 4 i = 4 vect[i] = 5 i = 5 vect[i] = 6 i = 6 vect[i] = 7 i = 7 vect[i] = 8 i = 8 vect[i] = 9 i = 9 vect[i] = 0
antherWay: i = 0 vect[i] = 1 i = 1 vect[i] = 2 i = 2 vect[i] = 3 i = 3 vect[i] = 4 i = 4 vect[i] = 5 i = 5 vect[i] = 6 i = 6 vect[i] = 7 i = 7 vect[i] = 8 i = 8 vect[i] = 9 i = 9 vect[i] = 10
How to Determine the Size of Array in C?
To determine the size of an array in terms of bytes, use the sizeof
operator. For example:
int a[10]; size_t size = sizeof(a);
So the size of array is 40 bytes as each int can take up 4 bytes each. In order to determine the length of array we can divide the size of array with the size of first element in array (size of array type i.e. int, char etc).
int a[10]; size_t size = sizeof(a) / sizeof(a[0]); //a[0] can be replaced with int, char depending upon array type.
The above situation is only valid if you are directly working with array in same function. However, as arrays are passed onto other functions as pointers so the above method will fail. This is because sizeof() will return the size of the pointer NOT the array.
Print the Size of an Array using sizeof Operator
The following program demonstrates the use of sizeof operator and prints the size of arrays before passing to to a function and with in the functions.
#include <stdio.h>
#include <stdlib.h>
void printSizeOf(int intArray[])
{
printf("sizeof of parameter: %d\n", (int) sizeof(intArray));
}
void printLength(int intArray[])
{
printf("Length of parameter: %d\n", (int)( sizeof(intArray) / sizeof(int) ));
}
int main(int argc, char* argv[])
{
int array[] = { 0, 1, 2, 3, 4, 5, 6 };
printf("sizeof of array: %d\n", (int) sizeof(array));
printSizeOf(array);
printf("Length of array: %d\n", (int)( sizeof(array) / sizeof(array[0]) ));
printLength(array);
}
How to Perform Read/Write Operations on Arrays?
Here is a more complex program that demonstrates how to read, write and traverse integer arrays in C programming. There is also another source code to compare two arrays in C.
#include <stdio.h>
void intSwap(int *x, int *y);
int getIntArray(int a[], int nmax, int sentinel);
void printIntArray(int a[], int n);
void reverseIntArray(int a[], int n);
int main(void) {
int x[10];
int hmny;
hmny = getIntArray(x, 10, 0);
printf("The array was: \n");
printIntArray(x,hmny);
reverseIntArray(x,hmny);
printf("after reverse it is:\n");
printIntArray(x,hmny);
}
void intSwap(int *x, int *y)
/* It swaps the content of x and y */{
int temp = *x;
*x = *y;
*y = temp;
}
/* n is the number of elements in the array a.
* These values are printed out, five per line. */void printIntArray(int a[], int n){
int i;
for (i=0; i<n; ){
printf("\t%d ", a[i++]);
if (i%5==0)
printf("\n");
}
printf("\n");
}
/* It reads up to nmax integers and stores then in a; sentinel
* terminates input. */int getIntArray(int a[], int nmax, int sentinel)
{
int n = 0;
int temp;
do {
printf("Enter integer [%d to terminate] : ", sentinel);
scanf("%d", &temp);
if (temp==sentinel) break;
if (n==nmax)
printf("array is full\n");
else
a[n++] = temp;
}while (1);
return n;
}
/* It reverse the order of the first n elements of array */void reverseIntArray(int a[], int n)
{
int i;
for(i=0;i<n/2;i++){
intSwap(&a[i],&a[n-i-1]);
}
}
How to Copy one Array into Another?
There is no such statement in C language which can directly copy an array into another array. So we have to copy each item separately into another array.
#include <stdio.h>
int main()
{
int iMarks[4];
short newMarks[4];
iMarks[0]=78;
iMarks[1]=64;
iMarks[2]=66;
iMarks[3]=74;
for(i=0; i<4; i++)
newMarks[i]=iMarks[i];
for(j=0; j<4; j++)
printf("%d\n", newMarks[j]);
return 0;
}
In summary, arrays offer a straightforward means to work with multiple elements of the same type. By utilizing an array variable, we can efficiently manage, modify, and store numerous elements of a consistent type, accessing them easily through indices.
Multidimensional Arrays in C
In C programming you can have arrays of any dimensions. To understand the concept of multidimensional arrays let us consider the following 4 X 5 matrix
Row number (i) | Column numbers (j) | |||||
---|---|---|---|---|---|---|
0 | 11 | 3 | 5 | -9 | -6 | |
1 | 5 | 6 | -8 | 7 | 24 | |
2 | -8 | 9 | 2 | 12 | 45 | |
3 | 10 | 13 | -10 | 4 | 5 |
Let us assume the name of matrix is x.
To access a particular element from the array we have to use two subscripts on for row number and other for column number the notation is of the form X [i] [j] where i stands for row subscripts and j stands for column subscripts. Thus X [0] [0] refers to 10, X [2] [1] refers to 16 and so on In short multidimensional arrays are defined more or less in the same manner as single dimensional arrays, except that for subscripts you require two squire two square brackets. We will restrict our decision to two dimensional arrays.
Here are are some typical two-dimensional array definitions:
float table [50][50]; char line [24][40];
The first example defines tables as a floating point array having 50 rows and 50 columns. The total number of elements in this array are 2500 (50 x 50).
The second declaration example establishes an array line of type character with 24 rows and 40 columns. The number of elements is 1620 (24 x 40).
Consider the following two dimensional array definition
int values [3] [4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. 11, 12 };
Values [0] [0] = 1 Values [0] [1] = 2 Values [0] [2] = 3 Values [0] [3] = 4 Values [1] [0] = 5 Values [1] [1] = 6 Values [1] [2] = 7 Values [1] [3] = 8 Values [2] [0] = 9 Values [2] [1] = 10 Values [2] [2] = 11 Values [2] [3] = 12
Here the first subscript stands for the row number and second one for column number. First subscript ranges from 0 to 2 and there are altogether 3 rows second one ranges from 0 to 3 and there are altogether 4 columns.
Alternatively the above definition can be defined and initialized as
int values [3] [4] = {
{ 1, 2, 3, 4 },
{ 5, 6, 7, 8 },
{ 9, 10, 11, 12 }
};
Here the values in first pair of braces are initialized to elements of first row, the values of second pair of inner braces are assigned to second row and so on. Note that outer pair of curly braces is required. If there are two few values within a pair of braces the remaining elements will be assigned as zeros.
Here is a sample program that stores roll numbers and marks obtained by a student side by side in matrix
#include <stdio.h>
main ( )
{
int stud [4] [2];
int i, j;
for (i =0; i < =3; i ++)
{
printf ("\n Enter roll no. and marks");
scanf ("%d%d", &stud [i] [0], &stud [i] [1] );
}
for (i = 0; i < = 3; i ++)
printf ("\n %d %d", stud [i] [0], stud [i] [1]);
}
The above example illustrates how a two dimensional array can be read and how the values stored in the array can be displayed on screen.
Here are some of the C Programs that use array. You can study these programs to further understand the concept of arrays and how to use them in your C programs.
- Print Fibonacci series in C
- Generating Random Number in C/C++
- Implementation of Base64 Encoding and Decoding in C
- Kruskal’s Algorithm Implementation in C
- Porter’s Algorithm in C
- Simple operations with arrays