w3resource

Arrays in C

Description

Suppose we want to store 50 student names of a class. One might try to declare 50 variables, say st_name0, st_name1,..,st_name49. However, it is much better to define all those names in a single variable, which is called an array.

- An array is a collection of data of the same type (and therefore, the same size) stored in consecutive memory cells under one name.

- An entire array is declared all at once.

- Each individual element in the array can be referenced by indexing. Indexed means the array elements are numbered and always start at 0.

In C, an element of an array (i.e., an individual data item) is referred to by specifying the array name followed by one or more subscripts, with each subscript enclosed in square brackets.

Declaring an Array

An array declaration is similar to the form of a normal declaration. The general form is :

typeName ArrayName[size] = { list of values }

This declares an array with the specified size, named ArrayName and type typeName. The array is indexed from 0 to (size-1). The size (in brackets) must be an integer literal or a constant variable. The compiler uses the size to determine how much space to allocate (i.e. how many bytes). Here are some examples :

int A[10];            // An array of ten integers; A[0], A[1], …, A[9]
char name[20];           // An array of 20 characters
float nums[50]; // An array of fifty floating numbers; nums[0], nums[1], …,nums[49]
int C[]; // An array of an unknown number of integers; C[0], C[1], …, C[size-1]
int table[5][10];        // A two dimensional array of integers

You can also declare an array in the following way :

#define ROLL_NUMBERS 51
  int  classv[ROLL_NUMBERS];
const int Emp_salary = 35
  float Employee[Emp_salary];

Example: int A[10];

  • Declares 10 integers and can be accessed by the name A
  • Each variable is assigned a unique location (location is also called as an index). The range of the location is 0 to (length – 1). For the said array range of the location is 0 to 9.

See the following diagram which represent the array A[10] :

Index 0 1 2 3 4 5 6 7 8 9
Value 15 8 14 45 48 45 -57 45 1 0

Indexing into Arrays

To refer a single array element use arrayname[index].

For example :

A[4] contains the value 48

A[9] contains the value 0

Indexed elements can be used just like simple variables.

printf(“%d\n”, A[4]); // print 48

Array elements and loops

Array elements are commonly used in for loops, see the following codes :

for(x=0; x < max; x++)
  A[x] = x*x;
sum = 0; 
  for(x=0; x < max; x++)
  sum += B[x];

Array Initialization

We declare normal variables in the following ways :

int x;
x = 0;
or
int x = 0;

In the case of an array, simply list the array values in set notation { }. Some valid array declarations are shown below.

int num[6] = {1, 3, 5, 7, 9, 11};
char letters[5] = {'a', 'b', 'c', 'd', 'e'};
float numbers[3] = {13.25, 12.09, 8.1};

Using Array Elements in Expressions

Array elements may be used wherever a variable of the same type may be used. See the following diagram and codes.

Example: int A[10];

Index 0 1 2 3 4 5 6 7 8 9
value 15 8 14 45 48 45 -57 45 1 0

x = A[1] * 2;     /* sets x to 16 */

A[4] = 88;    /* replaces 48 with 88 */

m = 6;

y = A[m];   /* sets y to –57 */

z = A[A[9]]; /* sets z to 15 */

Example -1:

There are seven numbers stored in an array. The following program prints all the numbers of that array as well as prints the numbers in backward.

#include<stdio.h>
int main()
{
int M[10];
int j;
/* store seven numbers in array M */
 M[0] = 2;
 M[1] = 4;
 M[2] = 6;
 M[3] = 8;
 M[4] = 10;
 M[5] = 12;
 M[6] = 14;
/* print numbers in M */
 printf("Print all the Numbers : \n");
 for (j = 0; j < 7; ++j)
 printf("M[%d] = %d\n",j,M[j]);
/* print numbers in M backwards */
 printf("\nFrom End to Beginning : \n");
 for (j = 6; j >= 0; --j)
 {
 printf("M[%d] = %d\n",j,M[j]);
  }
}

Output:

print an array

Example -2 :

The following program computes prime numbers between 1 to MXNO.

#include<stdio.h>
  #define MXNO 50
int main()
{
  int M[MXNO];
  int j, n;
 /* mark all numbers */
  printf("The prime numbers are :\n\n");
  for (j = 0; j < MXNO; ++j)
  {
  M[j] = 1;
  }
  for (j = 2; j < MXNO; ++j)
  {
  if (M[j])
  {
  printf("%d\n", j);
  }
  for (n = j+j; n < MXNO; n+= j)
  {
  M[n] = 0;
  }
  }
}

Copying arrays:

We have two arrays list1 and list2

int list1[6] = {2, 4, 6, 8, 10, 12};

int list2[6];

and we want to copy the contents of list1 to list2. For general variables (e.g. int x=3, y=5) we use simple assignment statement (x=y or y=x). But for arrays the following statement is wrong.

list2 = list1;

We must copy between arrays element by element and the two arrays must have the same size. In the following example, we use a for loop which makes this easy.

#include <stdio.h>
main()
int list1[6] = {2, 4, 6, 8, 10, 12};
int list2[6];
for (int ctr = 0; ctr<6; ctr++)
{
 list2[ctr] = list1[ctr];
}
 printf("Elements of list2 :\n"); 
 for (int ctr = 0; ctr<6; ctr++)
 {
  printf("%d ",list2[ctr]);
 }
}

Output:

Elements of list2 :
2 4 6 8 10 12

Two dimensional Array in C

A two-dimensional array can be used to represent a matrix, a table or board games (Tic Tac Toe, Sudoku etc). The row and column positions are given as successive indices. When you declare a variable of such an array, use a pair of square brackets for each dimension. See the following example :

// Declare a two-dimensional array with 3 rows and 2 columns
int table[3][2]:
// create and initialize  an array
int table[3][2] = { {10, 22}, {33, 44}, {45, 78} };

or

int table[3][2] = {10, 22, 33, 44, 45, 78 };

or

int table[3][2] = {
{10, 22},
{33, 44 },
{45, 78 }
 }; 

See the following diagram which represents the above array :

0 1
0 10 22
1 33 44
2 45 78

In the above array :

table[1][1] contains 22

table[2][0] contains 45

table[2][2] is "array out of bounds"

Printing a Two-dimensional array

To print all the elements of a two dimension array we use a doubly-nested for-loop. In the following example, there are 3 rows and 2 columns.

#include <stdio.h>
main()
{
  int row,col;
  int table[3][2] = { {10, 22}, {33, 44}, {45, 78} };
  for (row = 0; row < 3; row++)
  {
  for (col = 0; col < 2; col++)
  {
  printf("%d\t",table[row][col]);
  }
  printf("\n");
  } 
}

Output:

2d array

Previous: C do while loop
Next: C Pointer



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/c-programming/c-array.php