Arrays in C language

Introduction to arrays in c language

Arrays a kind of data structure that can store a sequential collection of fixed dimensions of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables such as number0, number 1, … and number99, declare a matrix variable such as numbers and use numbers [0], numbers [1] and …, numbers [99] to represent individual variables. A specific element in an array is accessed by an index.

All tables consist of contiguous memory locations. The smallest address corresponds to the first element and the highest to the last element.

List of article

  • Introduction to arrays in c language
  • Array statements
  • Array Initialization
  • Accessing Array Elements
  • Arrays in detail
  • Multidimensional Arrays
  • Two-dimensional arrays
  • Initialization of two-dimensional Array
  • Accessing two-dimensional elements
  • manage a two-dimensional array
  • Passing Arrays to function
  • Return Array From a function
  • Pointer to an Array


Array statements

To declare an array in C, a programmer specifies the type of elements and the number of elements required by an array as follows –

type arrayName [arraySize];

This is called a single dimensional array. ArraySize must be an integer constant greater than zero and the type can be any valid C data type. For example, to declare an array with 10 elements called a double balance sheet, use this statement –

double balance [10];

Here the balance is a variable array that is enough to hold up to 10 double numbers.

Array Initialization

You can initialize an array in C either one at a time or using a single statement as follows –

double balance [5] = {2000.0, 2.0, 3.4, 7.0, 50.0};

The number of values ​​in parentheses {} cannot be greater than the number of elements we declare for the array in square brackets [].

If you omit the array size, an array large enough to maintain the initialization is created. Therefore, if you write –

double balance [] = {2000.0, 2.0, 3.4, 7.0, 50.0};

You will create exactly the same picture as in the previous example. The following is an example to assign a single element to the array –

balance [4] = 50.0;

The above instruction assigns the fifth element in the array with a value of 50.0. All arrays have 0 as the index of their first element, which is also called the basic index, and the last index of an array will be the total size of the array minus 1. Shown below is the pictorial representation of the array we discussed above –


Accessing Array Elements

An item is accessed by indexing the array name. This is done by placing the index of the element in square brackets after the array name. E.g –

double salary = balance [9];

The above statement will take the tenth item in the table and assign the value of the salary variable. The following example shows how to use all three concepts mentioned above, ie. declaration, assignment and access to matrices –
Live demo

#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 + 200; 
/ * sets the item in location i to i + 100 * /

}

/ * subtract the value of each array element * /

for (j = 0; j <10; j ++) 

{
printf ("Element [% d] =% d \ n", j, n [j]);
}

return 0;

}

When the above code is compiled and executed, it produces the following result –

Element [0] = 200
Element [1] = 201
Element [2] = 202
Element [3] = 203
Element [4] = 204
Element [5] = 205
Element [6] = 206
Element [7] = 207
Element [8] = 208
Element [9] = 209

The sketches are important for C and should need much more attention. The following important matrix concepts should be clear to a C programmer –

Arrays in detail

Sr No.Concept and description
1Multidimensional Arrays
C supports multidimensional arrays. The simplest form of the multidimensional array is the two-dimensional array.
2Passing Arrays to function
You can function a pointer to an array by specifying the array name without an index.
3Return Array to a function
C allows a function to return an array.
4Pointer to an Array
You can generate a pointer to the first element of an array by simply specifying the array name without any index.

Multidimensional Arrays

The C programming language allows multidimensional Arrays. Here is the general form of a multidimensional matrix statement –

type name [size1] [size2] … [sizeN];

For example, the following statement creates an integer three-dimensional array –

int threedim [5] [10] [4];

Two-dimensional arrays

The simplest form of multidimensional board is two-dimensional board. A two-dimensional array is essentially a list of one-dimensional matrices. To declare a two-dimensional integer of size [x] [y], you would write something like this –

type arrayName [x] [y];

If the type can be any valid C data type and arrayName will be a valid C identifier. A two-dimensional array can be considered as a table that will have the number x of rows and the number of columns. A two-dimensional array a, containing three rows and four columns can be shown as follows –

Thus, each element in array a is identified by an element name of the form a [i] [j], where “a” is the name of the array, and “i” and “j” are the subscriptions that uniquely identify each element. from “a”.


Initialization of two-dimensional Array

Multidimensional matrices can be initialized by specifying the values ​​in parentheses for each row. A table with 3 rows follows and each row has 4 columns.

int a [3] [4] = { {0, 1, 2, 3}, / * initializers for row indexed with 0 * /
                  {4, 5, 6, 7}, / * initializers for row indexed with 1 * /
                  {8, 9, 10, 11} / * initializers for the indexed row with 2 * / };

Nest bracelets, which indicate the desired row, are optional. The next initialization is equivalent to the previous example –

int a [3] [4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Accessing two-dimensional elements

An element of a two-dimensional array is accessed using subscriptions, ie the row index and the column index of the array. E.g –

int val = a [2] [3];

The above statement will take the fourth element from the 3rd row of the table. You can check in the figure above. Let’s check the following program in which we used a nested loop to

manage a two-dimensional array –

#include <stdio.h>
 
int main () {

   /* an array with 5 rows and 2 columns*/
   int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
   int i, j;
 
   /* output each array element's value */
   for ( i = 0; i < 5; i++ ) {

      for ( j = 0; j < 2; j++ ) {
         printf("a[%d][%d] = %d\n", i,j, a[i][j] );
      }
   }
   
   return 0;
}

When the above code is compiled and executed, it produces the following result –

a [0] [0]: 0
a [0] [1]: 0
a [1] [0]: 1
a [1] [1]: 2
a [2] [0]: 2
a [2] [1]: 4
a [3] [0]: 3
a [3] [1]: 6
a [4] [0]: 4
a [4] [1]: 8

As explained above, you can have matrices with any number of dimensions, although it is likely that most matrices created by it have one or two dimensions.

Passing Arrays to function

If you want to pass a one-dimensional array as an argument to a function, you should declare a formal parameter in one of the following three ways, and all three declaration methods produce similar results, because each tells the compiler that an indicator the whole goes to be

received. Similarly, you can pass multidimensional arrays as formal parameters.

Way-1
Formal parameters as an indicator –

void myFunction(int *param) {
   .
   .
   .
}

Way 2
Formal parameters as dimensioned matrix –

void myFunction(int param[10]) {
   .
   .
   .
}

Way-3
Formal parameters as a non-specialized picture –

void myFunction(int param[]) {
   .
   .
   .
}

Example

Now consider the following function, which takes an array as an argument along with another argument and based on past arguments, returns the average of the numbers passed through the array as follows –

double getAverage(int arr[], int size) {

   int i;
   double avg;
   double sum = 0;

   for (i = 0; i < size; ++i) {
      sum += arr[i];
   }

   avg = sum / size;

   return avg;
}

Now, let’s call the function above, as follows –

/ * functio#include <stdio.h>
 
/* function declaration */
double getAverage(int arr[], int size);

int main () {

   /* an int array with 5 elements */
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   /* pass pointer to the array as an argument */
   avg = getAverage( balance, 5 ) ;
 
   /* output the returned value */
   printf( "Average value is: %f ", avg );
    
   return 0;
}

When the above code is compiled and executed together, it produces the following result –

The average value is: 214.4 million

As you can see, the length of the array does not matter in terms of function, because C does not meet the limits by checking the formal parameters.

Return Array From a function

C programming does not allow the return of an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array name without an index.

If you want to return a one-dimensional array from a function, you should declare a function by returning a pointer as in the following example –

int * myFunction() {
   .
   .
   .
}

The second point to note is that C does not plead to return the address of a local variable outside the function, so you should define the local variable as a static variable.

Now consider the following function that will generate 10 random numbers and return them using an array and call this function as follows –
Live demo

#include <stdio.h>

/* function to generate and return random numbers */
int * getRandom( ) {

   static int  r[10];
   int i;

   /* set the seed */
   srand( (unsigned)time( NULL ) );
  
   for ( i = 0; i < 10; ++i) {
      r[i] = rand();
      printf( "r[%d] = %d\n", i, r[i]);
   }

   return r;
}

/* main function to call above defined function */
int main () {

   /* a pointer to an int */
   int *p;
   int i;

   p = getRandom();
	
   for ( i = 0; i < 10; i++ ) {
      printf( "*(p + %d) : %d\n", i, *(p + i));
   }

   return 0;
}

When the above code is compiled and executed together, it produces the following result –

r [0] = 313959809
r [1] = 1759055877
r [2] = 1113101911
r [3] = 2133832223
r [4] = 2073354073
r [5] = 167288147
r [6] = 1827471542
r [7] = 834791014
r [8] = 1901409888
r [9] = 1990469526
(p + 0): 313959809
(p + 1): 1759055877
(p + 2): 1113101911
(p + 3): 2133832223
(p + 4): 2073354073
(p + 5): 167288147
(p + 6): 1827471542
(p + 7): 834791014
(p + 8): 1901409888
(p + 9): 1990469526

Pointer to an Array

It is very likely that you will not understand this section until you move on to the “Pointers” chapter.

Assuming you have some understanding of indicators in C, let’s start: a table name is a constant indicator to the first element of the table. Therefore, in the statement –

double balance [50];

balance is an indicator for & balance [0], which is the address of the first element of the array balance. Thus, the following program fragment assigns p as the address of the first element of balance –

double *p;
double balance[10];

p = balance;

It is legal to use the table name as a constant indicator and vice versa. Therefore, * (balance + 4) is a legitimate way to access balanced data [4].

After storing the address of the first element in “p”, you can access the elements of the array using * p, * (p + 1), * (p + 2) and so on. The following is an example to show all the concepts discussed above –
Live demo

#include <stdio.h>

int main () {

   /* an array with 5 elements */
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double *p;
   int i;

   p = balance;
 
   /* output each array element's value */
   printf( "Array values using pointer\n");
	
   for ( i = 0; i < 5; i++ ) {
      printf("*(p + %d) : %f\n",  i, *(p + i) );
   }

   printf( "Array values using balance as address\n");
	
   for ( i = 0; i < 5; i++ ) {
      printf("*(balance + %d) : %f\n",  i, *(balance + i) );
   }
 
   return 0;
}

When the above code is compiled and executed, it produces the following result –

Array values using pointer 
*(p + 0) : 1000.000000 
*(p + 1) : 2.000000 
*(p + 2) : 3.400000 
*(p + 3) : 17.000000 
*(p + 4) : 50.000000 
Array values using balance as address
 *(balance + 0) : 1000.000000 
*(balance + 1) : 2.000000 
*(balance + 2) : 3.400000 
*(balance + 3) : 17.000000 
*(balance + 4) : 50.000000

In the example above, p is an indicator for doubling, which means it can store the address of a double variable. Once we have the address in p, * p will give us the value available at the address stored in p, as we showed in the example above.

Leave a Comment