Chapter 7: Arrays and Strings

Introduction to Arrays

Arrays in C are used to store multiple values of the same type in a single variable, which is useful when you need to manage a large number of related data items. Arrays provide a way to access and manipulate this data efficiently using index-based access.

What is an Array?

An array is a collection of elements, each identified by an array index or subscript. All elements in an array share the same data type. The syntax for declaring an array in C is as follows:

data_type array_name[array_size];
  • data_type: The type of elements stored in the array (e.g., int, float, char).
  • array_name: The name of the array.
  • array_size: The number of elements the array can hold.

Declaring and Initializing Arrays

Declaration

To declare an array, you specify the type of its elements and the number of elements it will hold. For example, to declare an array of 5 integers:

int numbers[5];

Initialization

You can initialize an array at the time of declaration by providing a comma-separated list of values enclosed in braces:

int numbers[5] = {1, 2, 3, 4, 5};

If you do not specify the size, the compiler will determine it based on the number of values provided:

int numbers[] = {1, 2, 3, 4, 5}; // size is 5

Accessing Array Elements

Array elements are accessed using the array name followed by the index in square brackets. Array indices start at 0. For example, to access the first element of the array:

int firstElement = numbers[0]; // firstElement is 1

You can also modify an array element by assigning a new value to it:

numbers[2] = 10; // changes the third element to 10

Multi-dimensional Arrays

Arrays in C can have multiple dimensions. The most common multi-dimensional array is the two-dimensional array, often used to represent matrices or tables.

Declaring and Initializing Multi-dimensional Arrays

Declaration

To declare a two-dimensional array, you specify the type of its elements, the number of rows, and the number of columns:

int matrix[3][3];

Initialization

You can initialize a two-dimensional array at the time of declaration by providing nested braces with comma-separated values:

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

Accessing Multi-dimensional Array Elements

To access elements of a multi-dimensional array, you use multiple indices, one for each dimension:

int value = matrix[1][2]; // value is 6 (second row, third column)

You can also modify elements in a similar manner:

matrix[0][0] = 10; // changes the first element to 10

Strings in C

Strings are arrays of characters terminated by a null character ('\0'). In C, strings are often manipulated using arrays of characters.

Declaring and Initializing Strings

Declaration

To declare a string, you define a character array:

char name[10];

Initialization

You can initialize a string at the time of declaration using a string literal:

char name[] = "John"; // size is 5 (4 characters + null terminator)

You can also specify the size explicitly:

char name[10] = "John";

Accessing String Elements

String elements are accessed in the same way as array elements. For example, to access the first character of a string:

char firstLetter = name[0]; // firstLetter is 'J'

You can modify a character in the string:

name[1] = 'a'; // changes the string to "Jahn"

String Handling Functions

C provides several standard library functions for manipulating strings. These functions are declared in the string.h header file.

Example: strlen

The strlen function returns the length of a string (excluding the null terminator):

#include <stdio.h>
#include <string.h>

int main() {
char str[] = "Hello, World!";
printf("Length of the string: %lu\n", strlen(str));
return 0;
}

Example: strcpy

The strcpy function copies a string from source to destination:

#include <stdio.h>
#include <string.h>

int main() {
char src[] = "Hello, World!";
char dest[20];
strcpy(dest, src);
printf("Copied string: %s\n", dest);
return 0;
}

Example: strcat

The strcat function concatenates (appends) one string to another:

#include <stdio.h>
#include <string.h>

int main() {
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}

Example: strcmp

The strcmp function compares two strings. It returns 0 if the strings are equal, a positive value if the first string is greater, and a negative value if the second string is greater:

#include <stdio.h>
#include <string.h>

int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("Strings are equal\n");
} else if (result > 0) {
printf("First string is greater\n");
} else {
printf("Second string is greater\n");
}
return 0;
}

Practical Examples

Example 1: Sum of Array Elements

This function calculates the sum of elements in an integer array:

#include <stdio.h>

int sumArray(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}

int main() {
int numbers[] = {1, 2, 3, 4, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("Sum of array elements: %d\n", sumArray(numbers, size));
return 0;
}

Example 2: Finding the Maximum Element in an Array

This function finds the maximum element in an integer array:

#include <stdio.h>

int maxElement(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
return max;
}

int main() {
int numbers[] = {2, 8, 4, 1, 9, 5};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("Maximum element: %d\n", maxElement(numbers, size));
return 0;
}

Example 3: Reversing a String

This function reverses a given string:

#include <stdio.h>
#include <string.h>

void reverseString(char str[]) {
int n = strlen(str);
for (int i = 0; i < n / 2; i++) {
char temp = str[i];
str[i] = str[n - i - 1];
str[n - i - 1] = temp;
}
}

int main() {
char str[] = "Hello, World!";
reverseString(str);
printf("Reversed string: %s\n", str);
return 0;
}

Conclusion

Arrays and strings are powerful tools in C programming, enabling efficient handling of large datasets and text manipulation. Understanding how to declare, initialize, and manipulate arrays and strings is essential for developing complex applications. By mastering these concepts, you can write more robust and efficient programs.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *