C Programming
Unit 6: Arrays
Declaration, initialization, sorting, multidimensional arrays, and string handling functions.
Introduction
An array is a collection of elements of the same data type stored in contiguous memory locations. Instead of declaring many separate variables to hold related values, we group them under a single name and access each value through an index.
For example, to store the marks of 5 students you would otherwise need:
int m1, m2, m3, m4, m5;
With an array, the same data fits in one declaration:
int marks[5];
Key characteristics
- All elements share the same data type (
int,float,char, etc.). - Elements are stored in continuous memory, one after another.
- The index starts from
0and ends atsize - 1. - The size of an array is fixed at the time of declaration.
- Accessing any element takes constant time because the address can be calculated
directly:
address = base_address + index * sizeof(type).
Why use arrays?
- They make it possible to handle a large number of related values without dozens of variables.
- They allow looping over data using the index — perfect for searching, sorting, and processing collections.
- They are the foundation for more complex data structures like strings, matrices, stacks, and queues.
Declaration of array
The general syntax to declare a one-dimensional array is:
data_type array_name[size];
Here:
data_typeis the type of each element (e.g.,int,float,char).array_namefollows the usual rules for naming variables.sizeis a positive integer constant that specifies how many elements the array can hold.
Examples:
int marks[5]; /* an array of 5 integers */
float price[10]; /* an array of 10 floats */
char name[20]; /* an array of 20 characters */
Accessing elements
Each element of an array is accessed using its index inside square brackets []. The
first element has index 0, the second has index 1, and so on.
marks[0] = 90; /* assign 90 to the first element */
marks[1] = 85; /* assign 85 to the second element */
marks[4] = 75; /* assign 75 to the last element */
printf("%d\n", marks[0]); /* 90 */
printf("%d\n", marks[4]); /* 75 */
Note: C does not check whether the index is within bounds. Accessing
marks[10]in an array of size5is undefined behaviour — it may crash, print garbage, or silently corrupt data.
Initialization of array
An array can be initialized at the time of declaration by providing a list of values
inside curly braces { }.
Full initialization
int marks[5] = {90, 85, 70, 60, 95};
Each value goes into the array in order — marks[0] = 90, marks[1] = 85, and so on.
Size determined automatically
If the size is omitted, the compiler counts the values for you.
int values[] = {1, 2, 3, 4}; /* size becomes 4 */
Partial initialization
If fewer values are provided than the declared size, the remaining elements are
automatically set to 0.
int data[5] = {1, 2}; /* {1, 2, 0, 0, 0} */
Initialize all to zero
A common trick to set the whole array to zero:
int zeros[100] = {0}; /* every element becomes 0 */
Runtime initialization
You can also fill an array using a loop and user input.
Example — read and print an array:
#include <stdio.h>
int main(void)
{
int n, i;
int arr[100];
printf("Enter number of elements: ");
scanf("%d", &n);
printf("Enter %d elements:\n", n);
for (i = 0; i < n; i++)
scanf("%d", &arr[i]);
printf("Elements entered: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
Sorting
Sorting is the process of arranging the elements of an array in a particular order — either ascending (small to large) or descending (large to small). Sorting is one of the most common operations performed on arrays.
The simplest sorting technique is bubble sort, in which neighbouring elements are compared and swapped if they are in the wrong order. After each pass, the largest (or smallest) unsorted element “bubbles up” to its correct position.
Example — ascending order:
#include <stdio.h>
int main(void)
{
int arr[] = {5, 2, 8, 1, 4};
int n = 5, i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) { /* swap if out of order */
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Ascending: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]); /* 1 2 4 5 8 */
printf("\n");
return 0;
}
Example — descending order:
The only change is the comparison: use < instead of > so that the smallest element
bubbles to the end.
#include <stdio.h>
int main(void)
{
int arr[] = {5, 2, 8, 1, 4};
int n = 5, i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (arr[j] < arr[j + 1]) { /* reversed comparison */
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
printf("Descending: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]); /* 8 5 4 2 1 */
printf("\n");
return 0;
}
Multidimensional array
A multidimensional array is an array of arrays. The most common form is the two-dimensional array, which is used to represent tables, grids, and matrices.
Declaration
data_type name[rows][columns];
Example:
int matrix[3][4]; /* 3 rows and 4 columns */
float table[2][2]; /* 2 x 2 matrix of floats */
The total number of elements is rows * columns. For matrix[3][4], there are
3 * 4 = 12 integers stored in row-major order.
Initialization
A two-dimensional array can be initialized row by row using nested braces:
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
Or as a flat list, where the compiler fills row by row:
int matrix[2][3] = {1, 2, 3, 4, 5, 6};
Accessing elements
Each element is accessed using two indices — one for the row and one for the column.
matrix[0][0] = 10; /* first row, first column */
matrix[1][2] = 99; /* second row, third column */
printf("%d\n", matrix[0][0]);
Example — print a 2D array:
#include <stdio.h>
int main(void)
{
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++)
printf("%d ", matrix[i][j]);
printf("\n");
}
return 0;
}
Output:
1 2 3
4 5 6
Example — matrix addition
#include <stdio.h>
int main(void)
{
int a[2][2] = {{1, 2}, {3, 4}};
int b[2][2] = {{5, 6}, {7, 8}};
int c[2][2];
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
c[i][j] = a[i][j] + b[i][j];
printf("Sum matrix:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
printf("%d ", c[i][j]);
printf("\n");
}
return 0;
}
Strings and string-handling functions
In C, a string is a one-dimensional array of characters terminated by the special
null character '\0'. The null character marks the end of the string so that functions
know where to stop.
Declaring strings
char name[10] = "Ram"; /* stored as {'R','a','m','\0', ...} */
char city[] = "Kathmandu"; /* size automatically becomes 10 */
char letters[5] = {'H','i','\0'};/* manual character-by-character init */
The size of the array must be at least one more than the number of characters in the string, to make room for
'\0'.
Reading and printing strings
#include <stdio.h>
int main(void)
{
char name[30];
printf("Enter your name: ");
scanf("%s", name); /* reads until whitespace */
printf("Hello, %s!\n", name);
return 0;
}
scanf("%s", ...)stops at the first whitespace. To read a full line including spaces, usefgets(name, sizeof name, stdin);.
Common string-handling functions
C provides standard string functions declared in the header file <string.h>.
| Function | Purpose |
|---|---|
strlen(s) | Returns the length of s (excluding '\0'). |
strcpy(d, s) | Copies string s into d. |
strcat(d, s) | Appends string s to the end of d. |
strcmp(a, b) | Compares two strings. Returns 0 if equal. |
strrev(s) | Reverses string s (non-standard, in <string.h>). |
strlwr(s) | Converts s to lowercase (non-standard). |
strupr(s) | Converts s to uppercase (non-standard). |
Example — using string functions
#include <stdio.h>
#include <string.h>
int main(void)
{
char a[20] = "Hello";
char b[20] = "World";
char c[20];
/* Length */
printf("Length of a = %lu\n", strlen(a)); /* 5 */
/* Concatenation */
strcat(a, " ");
strcat(a, b);
printf("After strcat: %s\n", a); /* Hello World */
/* Copy */
strcpy(c, a);
printf("Copied to c: %s\n", c);
/* Compare */
printf("strcmp = %d\n", strcmp("abc", "abc")); /* 0 */
printf("strcmp = %d\n", strcmp("abc", "abd")); /* -1 */
return 0;
}
Example — counting characters without strlen
#include <stdio.h>
int main(void)
{
char s[] = "Programming";
int count = 0;
while (s[count] != '\0')
count++;
printf("Length = %d\n", count); /* 11 */
return 0;
}