C and C++ Programming Resources

Custom Search

Arrays in C Programming

What is an Array in C Language?

An array in C Programing Language can be defined as number of memory locations, each of which can store the same data type and which can be references through the same variable name.

An array is a collective name given to a group of similar quantities. 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 ints and 5 are floats.

Arrays and pointers have a special relationship as arrays use pointers to reference memory locations.

Declaration of an Array

Arrays must be declared before they can be used in the program. Standard array declaration is as

type variable_name[lengthofarray];

Here type specifies the variable type of the element which is going to be stored in the array. In C programmin language we can declare the array of any basic standard type which C language supports. For example

double height[10];
float width[20];
int min[9];
char name[20];

In C Language, arrays starts at position 0. The elements of the array occupy adjacent locations in memory. C Language 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 accesed any where from with in the program. So

m=height[0];

variable m will have the value of first item of array height.

The program below will declare an array of five integers and print all the elements of the array.

int myArray [5] = {1,2,3,4,5};
/* To print all the elements of the array
for (int i=0;i<5;i++){
   printf("%d", myArray[i]);
}

Initializing Arrays

Initializing of array is very simple in c programming. The initializing values are enclosed within the curly braces in the declaration and placed following an equal sign after the array name. 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.

int myArray[5] = {1, 2, 3, 4, 5}; //declare and initialize the array in one statement
int studentAge[4];
studentAge[0]=14;
studentAge[1]=13;
studentAge[2]=15;
studentAge[3]=16;

Performing operations on Arrays

Here is a program that will demonstrate the simple operations of the 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 this program is
   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
   */

Here is a more complex program that will demonstrate how to read, write and traverse the integer arrays

#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]);
   }
}

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 seperately 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;
}

To summarize, arrays are provides a simple mechanism where more than one elements of same type are to be used. We can maintain, manipulate and store multiple elements of same type in one array variable and access them through index.

Multidimensional Arrays

In C Language one 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 multi dimensional 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.

Below given 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 number of elements will be 2500 (50 X50).

The second declaration example establishes an array line of type character with 24 rows and 40 columns. The number of elements will be (24 X 40) 1920 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 initialised 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 initialised 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

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.

Tags: , ,

There are 89 Comments to this post. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response or TrackBack from your own site.

  • walle says:

    write a c++ program that recieves 5 integer from the user and display, sum, average, max and min the integer in a single line.

    Thanks,

  • Abiodun says:

    given a 5×5 array B of real values, Say
    3 2 -1 9 0
    0 1 5 6 7
    2 4 6 8 7
    -9 2 3 7 10
    -1 12 -3 -4 -5
    .using c programminmg language, write:
    1. a declaration for B
    2. An input Statement which will store the values
    3. A for-loop statement which computes the sum of its diagonal(TRACE) of the Matric B.
    4.a for statement which leaves the minimum value from B in a real variable named Bmin
    5.a function named TRACED which computes the trace of any nxn real array B, where n is less than 20.

  • pooh says:

    Please help me.
    write a program using string function that determine if the input word is a palindrome.A plindrome is a word that produce the same word when it is reversed.
    sample input/output dailog:

    enter a word:AMA
    reversed: AMA
    “it is palindrom”

    enter a word:STI
    reversed:ITS
    “it is not a palindrome”

    i really need this in october 8,2008..tnx

  • king Brian says:

    Write a program to perform the following
    a) Read in the data below
    b) Calculate and print to screen the total and average of each column
    c) Calculate and print to screen the maximum values in each column
    d) Calculate and print to screen the minimum values in each column
    To Submit

    6 -2
    5 -7
    5 -13
    50 8
    2 7
    3 3
    5 2

  • amrita kaur says:

    read a character array and print ist equivalent upper and lower case…??
    plss help….

    • Nadim Ansari says:

      #include
      #include
      void main()
      {
      char name[25];
      printf(“enter the name:”);
      scanf(“%s”,name);
      printf(“\n%s”,strlwr(name));
      printf(“\n%s”,strupr(name));
      getch();
      }

  • marianne says:

    hi…
    pls help me..about the c programming..
    create a program using 2 dimensional array and random nos..
    a bingo game..it is 5×5.

    • robin48gx says:

      The 2d array example in the `tutorial’ is syntactically incorrect.
      You need commas after the braces

      double array[4][4] = {
      { 1.2, 1.2, 1.3, 1.4 },
      { 1.2, 1.2, 1.3, 1.4 },
      { 1.2, 1.2, 1.3, 1.4 },
      { 1.2, 1.2, 1.3, 1.4 }
      };

      Is correct C syntax. Hope this helps.

  • lilkennblack says:

    please help.

    make a program that initiotalizes a 12 col and 12 row 2-2
    array to zero then allows the user to input any number between
    1 to 12 for the column and row it then “creates” the table on the 2d array
    and displays it

    *should trap all errors of nos. 1-12
    *allows users to repeat the program

    /*like a multiplication table*/

    i would appreciate this page if somebody helps me..thanks :)

  • nyakundi charles says:

    Help me to write a program to accept temperature entry in fahrenheit, convert it to celcius or vice versa.
    the program should also print the maximum and minimum of the temperature (°c of fahreiheit) entered.

  • shan says:

    pls help me….
    write a program reads 5 no.s into an array and prints out the value of each & every number which has a value less than 10

    • ambraham says:

      #include
      #include

      using namespace std;

      int main(int argc, char *argv[])
      {
      int a[5],i,value;
      printf(“Enter five numbers “);

      for(i=0;i<5;i++)
      {
      scanf("%d",&value);
      a[i]=value;
      }

      for(i=0;i<5;i++)
      {
      if(a[i]<10)
      {
      printf("The numbers less than ten are %d \n",a[i]);
      }
      else
      printf("This number is not less than ten \n ");

      }

      system("PAUSE");
      return EXIT_SUCCESS;
      }

  • divya says:

    hi
    i need an xample program for matrices.fro xample take an 8*8 matrix having o and 1 comination elements if we see 0 element in the matrix then we need to display the row and column number of that element………………….(but not the address of that element.)

  • divya says:

    A REAL-TIME PROGRAM
    hi
    i need an example program for matrices.for example take an 8*8 matrix having o and 1 combination elements if we see 0 element in the matrix then we need to display the row and column number of that element………………….(but not the address of that element.)
    PLZZZZZ give the answer……………………..

  • Hafiz says:

    Find the difference of two 2×2 matrics (A and B) input from keyboard and put the results in matrics C and display result. İs anybody about know this program Just give me an example how can i solve?

  • Omarion Gyasi says:

    write a c program to answer inquiries about students data. The program should display a menu that enables a user to,
    1.View all students records
    2. View a student record by ID
    3.Show the highest and lowest final scores
    Enter your choice:_\

    ID TEST 1 TEST 2 MID SEMESTER FINAL SCORE
    123 10 40 5 55
    457 13 30 10 43
    234 15 25 20 60
    345 12 24 19 55

    PLEASE SOMEONE SHOULD HELP ME OUT SOLVE THIS C PROGRAM. I HAVE ONLY 6 HOURS TO SUBMIT IT. THANKS

  • chel says:

    write a program using one dimensional array that accept five input values of a keyboard.then it should also accept a number to search.this number to be seacrhed if it is among the five input values. if it is, display themessage “searched number is found!”,otherwise display “searched number is lost!”

  • vincent says:

    Please help me.
    write a program using string function that determine if the input word is a palindrome.A plindrome is a word that produce the same word when it is reversed.
    sample input/output dailog:

    enter a word:AMA
    reversed: AMA
    “it is palindrom”

    enter a word:STI
    reversed:ITS
    “it is not a palindrome”

  • paolo2009 says:

    hi i know the answer to your question but before i give it can you pls tell me your n.a.s.l


Leave a Reply

You must be logged in to post a comment.