Computer Programming | Education

C Programming | Arrays

All the basics of Arrays in C programming language.

Arrays in C | Notes

Recommended Books for C Programming

To checkout books click on the images below

Basic Concept

Many applications require multiple data items that have common characteristics.

In mathematics, we often express such groups of data items in indexed form: X1, X2, X3, …, Xn

Why are arrays essential for some applications?

Take an example: Finding the minimum of a set of numbers.

From 3 numbers:

if ((a <= b) && (a <= c)) 
   min = a; 
   else
      if(b <= c) 
         min = b; 
      else 
         min = c;

From 4 numbers:

if((a <= b) && (a <= c) && (a <= d)) 
   min = a; 
   else 
       if((b <= c) && (b <= d)) 
           min = b; 
       else 
          if(c <= d) 
             min = c; 
          else 
             min = d;

The Problem

  • Suppose we have 10 numbers to handle.
  • Or 20,
  • Or 100
  • How to tackle this problem?
  • Solution –> Use Arrays

Using Arrays

All the data items constituting the group share the same name.

int x[10];

Individual elements are accessed by specifying the index.

  • X is a 10 element one-dimensional array
  • The name of the array also denotes the starting address of the array in memory.

Example:

int x[10];

  • x[0], x[1], x[2],… indicates the contents of the successive array locations.
  • x indicates the starting address in memory for the array.

Example through code:

#include<stdio.h> 
main(){ 
   int x[10]; 
   x[0] = 15; 
   x[1] = x[0] + 5; 
   printf(”\n%d %d %d %u \n”, x[0], x[1], x[2], x); 
}

Output:

15 20 1107384350 3221224640 
// 1107384350 Garbage Value
// 3221224640 Address

Declaring Arrays

Like variables, the arrays that are used in a program must be declared before they are used.

General syntax:

type array-name[size];

  • type specifies the data type of element that will be contained in the array (int, float, char, etc.).
  • size is an integer constant which indicates the maximum number of elements that can be stored inside the array.

Example: int marks[5];

  • marks is an array containing a maximum of 5 integers.

Examples :

  • int x[10];
  • char line[80];
  • float points[150];
  • char name[35]

If we are not sure of the exact size of the array, we can define an array of a large size. int marks[50]; .

Though in a particular run we may only be using, say, 10 elements.

How an array is stored in memory?

Starting from a given memory location, the successive array elements are allocated space in consecutive memory locations

x : starting address of the array in memory

k : number of bytes allocated per array element

Element a[i] :: allocated memory location at address x+i*k.

First array index assumed to start at zero.

Accessing Array Elements

A particular element of the array can be accessed by specifying two things:

  1. Name of the array.
  2. Index (relative position) of the element in the array.

In C, the index of an array starts from zero.

Example:

An array is defined as int x[10];

The first element of the array x can be accessed as x[0], fourth element as x[3], tenth element as x[9], etc.

The array index must evaluate to an integer between 0 and n-1 where n is the number of elements in the array.

Any integer expression can be given as the index.

  1. a[x+2] = 25;
  2. b[3*x-y] = a[10-x] + 5;

A Warning

In C, while accessing array elements, array bounds are not checked

Example:

int marks[5]; 
: 
: 
marks[8] = 75;

The above assignment would not necessarily cause an error.

Rather, it may result in unpredictable program results.

Initialization of Arrays

General form

type array_name[size] = {list of values};

Examples

int  marks[5] = {72, 83, 65, 80, 76}; 
char name[4] = {’A’, ’m’, ’i’, ’t’}; 

Some special cases

If the number of values in the list is less than the number of elements, the remaining elements are automatically set to zero.

float total[5] = {24.2, -12.5, 35.1}; 

total[0]=24.2, total[1]=-12.5, total[2]=35.1, total[3]=0, total[4]=0

The size may be omitted. In such cases the compiler automatically allocates enough space for all initialized elements.

int  flag[] = {1, 1, 1, 0}; 
char name[] = {’A’, ’m’, ’i’, ’t’};

Find the minimum of a set of 10 numbers

#include<stdio.h> 
main(){ 
   int  a[10], i, min; 
   for(i=0; i<10; i++) 
      scanf(”%d”, &a[i]); 
   min = 99999;    /* or, min=a[0] */ 
   for(i=0; i<10; i++){ 
      if(a[i] < min) 
         min = a[i]; 
   } 
   printf(”\n Minimum is %d”, min); 
}

#Alternate Version 1

change only one line to change the problem size

#include<stdio.h> 
#define size 10 
// change here
main(){ 
   int a[size], i, min; 
   for(i=0; i<size; i++) 
      scanf("%d”, &a[i]); 
   min = 99999; 
   for(i=0; i<size; i++){ 
      if(a[i] < min) 
         min = a[i]; 
   } 
   printf(”\n Minimum is %d”, min); 
}

#Alternate Version 2

Define an array of large size and use only the required number of elements

#include<stdio.h> 
main(){ 
   int a[100], i, min,n; 
   scanf("%d",&n);
   // number of elements
   for(i=0; i<n; i++) 
      scanf("%d”, &a[i]); 
   min = 99999; 
   for(i=0; i<n; i++){ 
      if(a[i] < min) 
         min = a[i]; 
   } 
   printf(”\n Minimum is %d”, min); 
}

Computing gpa

Handling two arrays at the same time

#include<stdio.h> 
#define  nsub  6 
main(){ 
   int grade_pt[nsub],cred[nsub],i,gp_sum=0,cred_sum=0; 
   float gpa; 
   for(i=0; i<nsub; i++) 
      scanf(”%d %d”, &grade_pt[i],&cred[i]); 
   for(i=0; i<nsub; i++){ 
      gp_sum += grade_pt[i] * cred[i]; 
      cred_sum += cred[i]; 
   } 
   gpa = (float) gp_sum / cred_sum; 
   printf(”\n GPA is: %f”, gpa); 
}

Things you cannot do

You cannot

  • use “=” to assign one array variable to another:
a = b;  /* a and b are arrays */ 
  • use “==” to directly compare array variables:
if (a == b)  ……… 
  • directly scanf or printf arrays:
printf (”……”, a);

How to copy the elements of one array to another?

By copying individual elements:

int a[25], b[25]; 
……         
for (j=0; j<25; j++) 
   a[j] = b[j];

How to read the elements of an array?

By reading them one element at a time.

int a[25]; 
…… 
for(j=0; j<25; j++) 
   scanf (”%f”, &a[j]); 
  • The ampersand (&) is necessary.
  • The elements can be entered all in one line or in different lines.

How to print the elements of an array?

By printing them one element at a time.

  • The elements are printed one per line.
for (j=0; j<25; j++) 
   printf (”\n %f”, a[j]); 
  • The elements are printed all in one line (starting with a new line).
printf (”\n”); 
   for (j=0; j<25; j++) 
      printf (” %f”, a[j]); 

If you are new to the C Programming and if you are willing to explore it, then you must visit our previous articles on C Programming.

  1. C Programming | String Functions
  2. C Programming | Character Strings



One Comment

  1. Hi, I do think this is an excellent website. I stumbledupon it 😉 I’m going to return yet again since i have bookmarked it. Money and freedom is the greatest way to change, may you be rich and continue to guide other people.

Leave a Reply