How2Lab Logo
tech guide & how tos..


Arrays in C Part 1 of 2 - Basic array declaration and manipulation


An array is a data structure composed of a fixed number of components of the same type which are organized in a linear sequence. A component of an array is selected by assigning an integer value to its index (or subscript) which identifies the position of the component in the sequence. In C, arrays are intimately related to pointers. All sorts of array manipulations can also be performed by using pointers, which will be discussed later.


Array Declaration

The syntax of array declaration is as follows,

{<storage class>} data type <array_name>[expression]{[expression]}; 

In the above, curly braces indicate optional parts of the declaration.

Example:int arr[10];

The above declaration defines an array called arr of size 10, i.e., arr consists of 10 elements of same data type int. The elements occupy consecutive cells in the memory (each cell houses one element) and forms an ordered set of elements. Each element can be identified by its position in the array, and is also referred as the subscript of the array. The first element is at position 0 and nth element can be found in the (n -1)th position.

The name of the array is arr, which contains the address of the first element (i.e. &arr[0]) of the array. However, an array name such as arr differs from an ordinary pointer variable (likeint *p;), because, it is static in nature and cannot point to a new memory location other than what it is pointing to by virtue of the declaration.


More examples of array declaration:
static float grade[10];
char name[20]; 

Array Manipulation

The most convenient way of performing array manipulation is to use the for repetitive construct (for loop) for accessing elements of the array.

The following example illustrates the usage of an array in implementing addition of two vectors:

#include <stdio.h> 
#define dimension 100 
typedef int vector[dimension];

main()
{
	vector vect_1, vect_2, result_vect;
	int i,n; 
	printf("Enter the Vector dimension: "); 
	scanf("%d", &n); fflush(stdin); 

	/* Accept values for the two arrays vect_1 & vect_2 */
	for(i=0; i < n; i++) 
	{
		printf("Give Vector element #%d: ", i+1);
		scanf("%d %d", &vect_1[i], &vect_2[i]); fflush(stdin);
		result_vect[i] = 0; //initialize elements of array result_vect to 0
	}

	/* Add vectors and create resultant vector */
	for(i=0; i < n; i++)
		result_vect[i] += (vect_1[i] + vect_2[i]);

	/* Display the resultant matrix */
	printf("\n\n");
	for(i = 0; i < n; i++)
	{
		printf("%d\t", result_vect[i]);
	}
	printf("\n"); 
}

How to initialize array elements during declaration?

Array initialization can be performed in the following way:

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

Note, however, that this definition-cum-initialization is permitted only in case of external variable definition. To include such initialization statement inside a function, storage class clause static has to be used as a prefix. See examples below.


Describe the output generated by each of the following programs.

#include <stdio.h> 
main()
{
	int i;
	int a, sum = 0;

	//declaring & initializing within a function
	static int x[10] = {9,8,7,6,5,4,3,2,0};

	for(i = 0; i < 10; ++i)
		if((i % 2) == 0)
			sum += x[i];
	printf("%d", sum);
}
#include <stdio.h> 
#define  ROWS  3
#define  COLS  4

//external declaration & initialization
int x[ROWS][COLS] = {12,11,10,9,8,7,6,5,4,3,2,1};

main()
{
	int i, j, max;
	for(i = 0; i < ROWS; ++i)
	{
		max = 9999;
		for(j = 0; j < COLS; ++j)
			if(x[i][j] < max)
				max = z[i][j];
		printf("%d", max);
	}
}

Exercises

Identify the errors in the following C program (if any) which initializes an array such that each of its ten elements is assigned with 0 value.

main()
{
	int num_arr[10], i = 0;
	...
	...	
	for(; ++i < 10; num_arr[i] = 0);
}

Identify the array defined in each of the following statements. Indicate what values are assigned to the individual array elements.

char game[7] = {'C', 'R', 'I', 'C', 'K', 'E', 'T'};
char match[] = "Football";

Write an appropriate array definition for each of the following cases:

  1. Define a one dimensional, integer array called A with 10 elements and initialize the array elements with 2, 5, 8, 11, ... , 29.
  2. Create a one dimensional, four element character array called object and assign the characters 'C', 'I', 'R', 'C', 'L' and 'E' to the array elements.
  3. Define a one dimensional, six element floating point array called flt_const having following initials values - 2.005, -3.05452, -1e-4, 340.179, 0.3e8, 0.023415

Lab work

Write a C program that will accept a line of text as input, store it in an array, and then print it backwards. Assume that the length of the string cannot exceed 80 characters, and while entering the data, the string will be terminated by a carriage return. Test the program by entering a suitable message.


Representing a string as a character array

A string constant, enclosed within a pair of double quotes, consists of 0 (empty string) or more characters terminated by a null ('\0') character, which indicates the end of the string.

The following statement in C defines a string variable:

char name[21]; 

The above declaration allocates a 21 character space in memory which can store 20 characters each of one byte (with name[0] as the starting element). One extra byte (the last element) is used to store the null character. The null character, represented by \0 serves the purpose of indicating the end of string. The string name can be initialized during declaration, by a string constant.


Example:

#include <stdio.h> 
main()
{
	static char name[22] = "Ratindra Nath Bhaskar";
	printf("%s\n", name);
	printf("Enter a new name: ");
	scanf("%s", name); fflush(stdin);
	printf({"\nThe new name is %s\n", name);
}

The above program displays the content of the variable name i.e. Ratindra Nath Bhaskar and allows the user to accept a new name in the same variable, and finally comes out of the program displaying the new name on the screen. Notice the absence of the & operator as a prefix of the variable name in the scanf statement, which requires the address of the variable. This is because the variable name itself stores the address of the string variable. This will be more clear from the following figure which shows the representation of the array name in the memory.


The variable name is a static pointer which stores the address of the first element of the name array i.e &name[0]. A static pointer means it cannot be reassigned with a new value.

From the above discussion it is obvious that a string variable requires only the starting address of the memory location where the string constant is located, because the end of the string is always indicated by the null character (\0).

To appreciate how this fact is utilized, look at the following example, where characters are read one by one from the console and stored in a characer array.

#include <stdio.h> 
#define  size  100 
char name[size];

main()
{
	int count = 0;
	char c; 
	while((c = getchar()) != '\n')
	{
		name[count] = c;
		++count; 
	}
	name[ count] = '\0';
}

Passing array to a function

An array name can be used as an argument to a function, thus permitting the entire array to be passed to the invoked function. The array name must appear by itself (without brackets or subscript) as an actual argument during the function call. The function's formal parameter is also written in the same manner, though it must be declared as an array within the formal parameter declaration. When a one dimensional array is used as a formal parameter, in the function declaration array name is written with a pair of empty square brackets. The size of an array is not specified within the formal parameter declaration. Since array name identifies the address of the first element, specifying array name as a parameter to a function essentially implements call by reference mode of parameter transfer.

Example:

A C program to read a set of numbers and sort them. It sorts a one dimensional integer array in ascending order.

#include <stdio.h> 
#define  dimension  100

main()
{
	int i, k, data[dimension];
	void bubble_sort(int m,int a[]);
	void read_data(int n, int x[]);
	printf("\nEnter the number of elements to be sorted: ");
	scanf("%d", &k); fflush(stdin); 
	read_data(k, data);
	bubble_sort(k, data);
	printf("\n\nSorted data elements are:\n");
	for(i=0; i < k; i++)
		printf("i = %d, data = %d\n", i+1, data[i]); 
}

/* Read an array of integer */ 
void read_data(int n, int x[])
{
	int j; 
	for(j=0; j < n ; j++)
	{
		printf("\nEnter data element #%d: ", j+1);
		scanf("%d", &x[j]); fflush(stdin);
	}
	return;
}

/* Sort an integer array a of m elements in ascending order */
void bubble_sort(int m, int a[])
{
	int  i, j, temp;
	int not_sorted = 1; //not_sorted is true when the array a is not sorted
	j = m;

	while(not_sorted)
	{
		not_sorted = 0; //assume sorted

		for(i=0; i < j-1; ++i) 
		{
			if(a[i] > a[i+1])
			{
				temp = a[i];
				a[i] = a[i+1];
				a[i+1] = temp;
				not_sorted = 1;	//data was not sorted
			}
		}
		--j;
	} //repeat until sorted
	return;
}

Share:
Buy Domain & Hosting from a trusted company
Web Services Worldwide | Hostinger
About the Author
Rajeev Kumar
CEO, Computer Solutions
Jamshedpur, India

Rajeev Kumar is the primary author of How2Lab. He is a B.Tech. from IIT Kanpur with several years of experience in IT education and Software development. He has taught a wide spectrum of people including fresh young talents, students of premier engineering colleges & management institutes, and IT professionals.

Rajeev has founded Computer Solutions & Web Services Worldwide. He has hands-on experience of building variety of websites and business applications, that include - SaaS based erp & e-commerce systems, and cloud deployed operations management software for health-care, manufacturing and other industries.


Refer a friendSitemapDisclaimerPrivacy
Copyright © How2Lab.com. All rights reserved.