Array


Introduction

Array is a group of same type of variables that have common name. Each item in the group is called an element of the array. Each element is distinguished from another by an index. All elements are stored contiguously in memory. The elements of the array can be of any valid type, such as, integers, characters, floating-point types or user-defined types. 

Array Declaration

Arrays are declared as other variables with the array size (total no of elements) enclosed in
square brackets. For example,
int x[100];
creates an integer array named x with 100 elements.
char text[80];
This creates a character array named text with 80 elements.
Note: The size of the array specified must be a constant.

 Array Indices

Each array elements are distinguished with an index. The index of first element is 0; the second element has an index of 1 and so on. The last element has an index of arraysize-1. For example,
int c[12];
creates an array named c with variables ranging from c[0] to c[11].
0
1
2
3
4
5
6
7
8
9
10
11
In the figure above, the index of the first element is 0, second is 1, and the last is 11. The first element is c[0], second is c[1], and the last is c[11]. 

 Arrays in Memory

The amount of storage required to hold an array is directly related to its type and size. We can use the following formula to find the total amount of storage:
Total size of array in bytes = sizeof(base type) × length of array
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element.

 Manipulating (Accessing) Arrays

Single operations that involve entire arrays are not permitted in C. Each array must be manipulated on an element-by-element basis. To access an element, specify the index of the element after array name enclosed in square brackets, such as, a[2]. Index must be an integral expression. Array elements are like normal variables. For example,
c[0] = 3;
printf( "%d", c[ 0 ] );
We can perform operations in subscript. If x equals 3, then
c[ 5 - 2 ] == c[ 3 ] == c[ x ]

Examples of Array Declaration and Manipulating

Example: Program to find sum and average of 10 integer number

#include<stdio.h>
#include<conio.h>
#define NUM 10
void main(void)
{
int grade[NUM],i,sum=0;
float avg;
clrscr();
printf("Input scores:\n");
for (i=0;i<NUM;i++){
scanf("%d",&grade[i]);
sum=sum+grade[i];
}
avg=(float)sum/NUM;
printf("Average=%f\n",avg);
getch();
3
}

Example: Program to calculate total stock value if price and stock of 5 different bulbs are given

#include<stdio.h>
#include<conio.h>
void main()
{
int i,stock[5];
float price[5], total = 0;
for (i=0;i<5;i++)
{
printf("Enter stock of bulb %d: ", i+1);
scanf("%d", &stock[i]);
printf("Enter price of bulb %d: ", i+1);
scanf("%f", &price[i]);
total += stock[i]*price[i];
}
printf("The total stock value is %f\n", total);
getch();
}

Initializing Arrays

Each array element can be initialized, when an array is declared. The initial values must appear in the order in which they will be assigned to the individual array elements, enclosed in braces and separated by commas. For example,
int digits[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
float x[6] = {0, 0.25, 0, –0.50, 0, 0};
When the list of initialization is shorter than the number of array elements to be initialized, the remaining elements are initialized to zero. For example,
int digits[10]={3,3,3};
Here, the elements in digits[3] to digits[9] will have value 0.
The array size can be omitted if you initialize the array elements
4
int digits[] = {1, 2, 3, 4, 5, 6};
The size of digits is 6.

Array Searching

We use array searching to find which (if any) array element have value equals to a given target value. There are two techniques for array searching: linear (or sequential) search and binary search.
In linear search, each array element value is compared to the target value one by one from first index to last index until we find the matched value. Useful for small and unsorted arrays
Binary Search can be used only on sorted arrays. First it compares the target value with the middle element value of the array, if not found one-half of the array is searched in the similar way and one-half is skipped. We continue the same process until we find the matched value.
Example: Sequential search
#include<stdio.h>
#include<conio.h>
#define SIZE 20
void main()
{
int a[SIZE],n,i,target;
clrscr();
printf("How many numbers?");
scanf("%d",&n);
printf("Enter numbers:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter number to search:");
scanf("%d",&target);
for(i=0;i<n;i++)
if(a[i]==target) {
printf("Found at index %d",i);
break;
}
5
if(i==n)
printf("Not found");
getch();
}
Example: Binary search
#include<stdio.h>
#include<conio.h>
#define SIZE 20
void main(void)
{
int a[SIZE],i,n,target,hi,low,mid;
clrscr();
printf("How many numbers?");
scanf("%d",&n);
printf("Enter numbers in ascending order:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("Enter a number to search:");
scanf("%d",&target);
low=0;
hi=n-1;
while(low<=hi)
{
mid=(low+hi)/2;
if(a[mid]==target)
{
printf("Found at index %d",mid);
break;
}
else if(a[mid]<target)
low=mid+1;
6
else
hi=mid-1;
}
if(low>hi)
printf("Not found");
getch();
}

 Array Sorting

The process of arranging the elements such that they are according to some strict order (ascending or descending) is called sorting. This can be accomplished using a technique known as bubble sort.
The basic idea of this sort is to pass the array sequentially n -1 times, where n is number of elements to sort. Each pass consists of comparing each element in the array with its successor (for example a[i] with a[i + 1]) and interchanging the two elements if they are not in the proper order. For example,
#include<stdio.h>
#include<conio.h>
#define SIZE 20
void main()
{
int a[SIZE],n,i,j,temp;
clrscr();
printf("How many numbers?");
scanf("%d",&n);
printf("Enter numbers:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
{
7
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
printf("Sorted array is:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
}

 Strings

Strings are one dimensional arrays of type char. By convention, a string in C is terminated by the end-of-string sentinel \0 or null character. Its decimal value is 0. When declaring a character array to hold a string, declare it to be one character longer than the largest string that it will hold. For example
char str[11];
declares an array str that can hold a 10-character string.
String constants are written between double quotes. For example, “abc” is a character array of size 4, with the last element being the null character \0. Notice that string constants are different from character constants. For example, “a” and „a‟ are not the same. The array “a” has two elements, the first with a value „a‟ and the second with value „\0‟. We can initialize strings as follows:
char name[8] = “Nawaraj”;
OR
char name[8] = {„N‟, „a‟, „w‟, „a‟, „r‟, „a‟, „j‟, „\0‟};
5.6.1. Reading Strings:
We can use both gets and scanf to read strings. For example,
char text[80];
gets(text);
OR
char text[80];
scanf(" %[^\n]“,text) //Reads characters until newline encountered
8
OR
char text[80];
scanf("%s", text); //Reads characters until whitespace encountered
Note: Null character is automatically appended at the end of the string.
5.6.2. Writing Strings:
We can use both puts and printf to write strings. For example,
puts(text);
printf("%s", text);
Example: Code to find length of a string
char text[80];
int len;
gets(text);
len = 0;
while (text[len] != '\0')
len++;
printf("The string \"%s\" has %d characters", text, len);
Example: Code to convert uppercase to lowercase
char text[80];
int i=0;
gets(text);
While(text[i] != '\0„)
{
if (text[i]>='a' && text[i]<='z')
text[i] = text[i]-32;
i++;
}
puts(text);
Example: Code to copy strings
char str1[80], str2[80];
9
int i;
gets(str1);
for (i=0; str1[i] != '\0'; i++)
{
str2[i] = str1[i];
}
str2[i] = '\0„;
puts(str2);
Example: Code to concatenate strings
char str1[80],str2[80];
int len1=0,len2=0;
printf("Enter two strings:\n");
gets(str1);
gets(str2);
while(str1[len1]!='\0')
len1++;
while(str2[len2]!='\0')
{
str1[len1]=str2[len2];
len1++;
len2++;
}
str1[len1]='\0';
puts(str1);

String Functions

The standard C library defines a wide range of functions that manipulate strings. Some functions are discussed below:
 strcpy(s1,s2) – Copies the string in s2 into s1
 strcat(s1,s2) – Concatenates the string s2 onto the end of the string s1
 strlen(s1) – Returns the number of characters in the string s1 excluding the terminating null character
10
 strcmp(s1,s2) – Compares the strings s1 and s2. Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s1
 strupr(s1) – Converts the string s1 to uppercase
 strlwr(s1) – Converts the string s1 to lowercase
Note: All string functions use the standard header string.h.
Example:
char str1[20] , str2[20];
gets(str1);
gets(str2);
int len = strlen(str1); //returns length of str1
printf("Length of str1=%d\n”,len));
strcat(str1,str2); //concatenates str2 and the end of str1
puts(str1);

Multi-dimensional Arrays

The C language allows arrays of arrays called multidimensional array. With two bracket pairs, we obtain two-dimensional array, with three bracket pairs, we obtain three-dimensional array, and so on. Hence, number of subscript determines the dimension of the array. For example, int a[2][3]; is a two dimensional array and int a[2][3][5]; is a three dimensional array.

Two-dimensional Arrays

A two-dimensional array is an array of one-dimensional arrays. For example, int a[3][4]; is an array of 3 elements, in which every element is an array of 4 integers. We can access elements of two-dimensional arrays using two indices. For example, a[0][1] gives the second integer within the first array and a[1][2] gives the third integer within the second array.
11
Think two-dimensional arrays as tables/matrices arranged in rows and columns. Use first subscript to specify row number and the second subscript to specify column number.
Example: Matrix addition
#include<stdio.h>
#include<conio.h>
void main()
{
int a[2][3],b[2][3],c,i,j;
clrscr();
printf("Input first matrix:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
printf("Input second matrix:\n");
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&b[i][j]);
printf("Addition matrix is:\n");
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
c=a[i][j]+b[i][j];
printf("%d\t",c);
}
printf("\n");
}
getch();
}
12

Two-dimensional array initialization

List the values separated by commas and enclosed in braces. For example, int a[2][3] = { 1, 2, 3, 4, 5, 6}; The values will be assigned in the order they appear. Initializers can be grouped with braces. For example, int a[2][3] = { {1, 2, 3}, {4, 5, 6}};
If not enough, unspecified elements set to zero. For example, int a[2][3] = { {1, 2}, {3, 4}}; You can also leave the size for first subscript. For example, int a[][3] = { {1, 2}, {3, 4}};
1
2
0
3
4
0
Multi-dimensional Arrays in Memory
Each array within a multidimensional array stored sequentially in memory as with one-dimensional array. For two-dimensional array, all elements in first row is stored, then the elements of second row and so on.

Arrays of Strings

You can create array of strings using a two-dimensional character array. Left dimension determines the number of strings, and right dimension specifies the maximum length of each string. For example,
char months[12][10];
Now you can use the array months to store 12 strings each of which can have a maximum of 10 characters (including the null). To access an individual string, you specify only the left subscript. For example, gets(monts[2]); provides input to third row and puts(months[2]); prints the string in third row.
1
2
3
4
5
6
13

Initializing arrays of strings:

We can initialize arrays of strings by listing the string constants separated by commas and enclosed in curly braces. For example,
char months[12][10] = {"January","February","March","April", "May","June","July","August",
"September","October","November","December"};
Passing Arrays to Functions
Arrays can also be used as arguments to functions. For example,
 Function declaration – Array arguments are represented by the data type and sizes of the array. For example, int add(int a[5]); OR int add(int a[]); for one dimensional array and int add(int a[2][3],int b[2][3]); OR int add(int a[][3],int b[][3]); for two dimensional array.
 Function call – When function is called, only the name of the array is used as argument. For example, add(a); add(a,b);
 Function definition – For one dimensional array, we define function as follows:
int add(int a[]) int add(int a[5])
{ {
………. OR ………….
} }
14
And for two dimensional arrays, we define as follows:
int add(int a[][3]) int add(int a[2][3])
{ {
………. OR ……..
} }
Example: Passing one-dimensional array to functions
#include<stdio.h>
#include<conio.h>
#define SIZE 5
int i,s;
void main()
{
int a[SIZE],add(int a[]);
printf("Enter %d elements:\n",SIZE);
for(i=0;i<SIZE;i++)
scanf("%d",&a[i]);
s=add(a);
printf("Sum=%d",s);
getch();
}
int add(int a[])
{
for(i=0;i<SIZE;i++)
s=s+a[i];
return s;
}
Example: Passing two-dimensional array to functions
#include<stdio.h>
#include<conio.h>
int i,j,c;
void main()
15
{
int a[2][3],b[2][3];
void input(int a[][3]);
void add(int a[][3],int b[][3]);
clrscr();
printf("Input first matrix:\n");
input(a);
printf("Input second matrix:\n");
input(b);
printf("Addition matrix is:\n");
add(a,b);
getch();
}
void input(int a[][3])
{
for(i=0;i<2;i++)
for(j=0;j<3;j++)
scanf("%d",&a[i][j]);
}
void add(int a[][3],int b[][3])
{
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
{
c=a[i][j]+b[i][j];
printf("%d\t",c);
}
printf("\n");
}
}

No comments:

Post a Comment