Arrays and strings are fundamental data structures in the C programming language. Understanding them thoroughly is essential for any programmer aiming to become proficient in C. This chapter will take you from the basics of arrays and strings to more advanced concepts, providing examples and explanations along the way.
An array is a collection of elements of the same data type arranged in contiguous memory locations. Each element in the array is accessed by its index. The index of the first element in C arrays starts from 0.
In C, you declare an array by specifying the data type of its elements and the number of elements it can hold. The syntax for declaring an array is:
Here, datatype
represents the data type of the elements, arrayName
is the name of the array, and arraySize
is the number of elements in the array.
datatype arrayName[arraySize];
int numbers[5]; // Declaration of an integer array of size 5
Arrays can be initialized at the time of declaration or later using loops or individually.
int numbers[5]; // Declaration of an array of integers with size 5
int data[3] = {10, 20, 30}; // Declaration and initialization of an array
char vowels[] = {'a', 'e', 'i', 'o', 'u'}; // Declaration and initialization of an array without specifying size
You can access individual elements of an array using their indices. Remember, array indices start from 0.
int numbers[5] = {1, 2, 3, 4, 5};
printf("%d", numbers[0]); // Output: 1
You can also modify the elements of an array by assigning new values to them using their indices.
numbers[2] = 10;
printf("%d", numbers[2]); // Output: 10
Array traversal involves visiting each element of the array and performing some operation. This is typically done using loops.
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
// Output: 1 2 10 4 5
You can search for a specific element in an array using linear search or binary search algorithms.
int search(int arr[], int n, int key) {
for (int i = 0; i < n; i++) {
if (arr[i] == key)
return i; // Element found
}
return -1; // Element not found
}
Multi-dimensional arrays are arrays of arrays. They are useful for representing tables, matrices, etc.
int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
printf("%d", matrix[0][0]); // Output: 1
#include
int main() {
// Declaration and initialization of a 3x3 matrix
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Accessing and printing elements of the matrix
printf("Matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
return 0;
}
A 3D array is an array of arrays of arrays. It’s like having a collection of 2D arrays. You can think of it as a cube with rows, columns, and depth.
In C, you declare and initialize a 3D array similar to how you declare 1D or 2D arrays, but with an additional dimension.
int cube[2][3][4];
cube[0][1][2] = 10;
#include
int main() {
// Declaration and initialization of a 3x3x3 3D array
int cube[3][3][3] = {
{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}},
{{10, 11, 12}, {13, 14, 15}, {16, 17, 18}},
{{19, 20, 21}, {22, 23, 24}, {25, 26, 27}}
};
// Accessing and printing elements of the 3D array
printf("Cube:\n");
for (int i = 0; i < 3; i++) {
printf("Layer %d:\n", i + 1);
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
printf("%d ", cube[i][j][k]);
}
printf("\n");
}
printf("\n");
}
return 0;
}
Note – you can increase arrays upto any dimension depending upon your need of storing the data
Example – int Array[a][b][c]….[k]
A string is a sequence of characters stored in contiguous memory locations. Unlike some other programming languages, C doesn’t have a built-in string data type. Instead, strings are represented as arrays of characters terminated by a null character (‘\0’). This chapter will cover everything you need to know about working with strings in C, from basic concepts to more advanced techniques.
Strings in C can be declared as character arrays.
#include
int main() {
char str1[] = "Hello";
char str2[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
printf("str1: %s\n", str1);
printf("str2: %s\n", str2);
return 0;
}
// output //
str1: Hello
str2: Hello
char str[] = "Hello"; // Initializing string at declaration
You can read strings from the user using scanf()
or gets()
function.
#include
int main() {
char name[20];
printf("Enter your name: ");
gets(name); // Deprecated, use fgets instead
printf("Hello, %s!\n", name);
return 0;
}
Strings can be printed using printf()
function with %s
format specifier.
#include
int main() {
char str1[] = "Unicorn";
printf("str1: %s\n", str1);
return 0;
}
To find the length of a string, you can use the strlen()
function from the <string.h>
library.
#include
#include
int main() {
char str[] = "Hello";
int length = strlen(str);
printf("Length of str: %d\n", length);
return 0;
}
// output //
Length of str: 5
Y0ou can concatenate strings using the strcat()
function from the <string.h>
library.
#include
#include
int main() {
char str1[20] = "Hello";
char str2[] = " World";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
// output //
Concatenated string: Hello World
You can copy strings using the strcpy()
function from the <string.h>
library.
#include
#include
int main() {
char source[] = "Hello";
char destination[20];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}
// output //
Copied string: Hello
You can compare strings using the strcmp()
function from the <string.h>
library.
#include
#include
int main() {
char str1[] = "apple";
char str2[] = "banana";
int result = strcmp(str1, str2);
if (result == 0)
printf("Strings are equal\n");
else if (result < 0)
printf("str1 is less than str2\n");
else
printf("str1 is greater than str2\n");
return 0;
}
// output //
str1 is less than str2
You can tokenize strings using the strtok()
function from the <string.h>
library.
#include
#include
int main() {
char str[] = "apple,banana,grape";
char *token = strtok(str, ",");
while (token != NULL) {
printf("%s\n", token);
token = strtok(NULL, ",");
}
return 0;
}
// output //
apple
banana
grape
You can search for substrings within strings using the strstr()
function from the <string.h>
library.
#include
#include
int main() {
char str[] = "Hello, World!";
char *substr = strstr(str, "World");
printf("Substring: %s\n", substr);
return 0;
}
// output //
Substring: World!
Arrays and strings are fundamental concepts in C programming. Mastering them opens the door to understanding more complex data structures and algorithms. With the knowledge gained from this chapter, you'll be better equipped to tackle a wide range of programming challenges efficiently. Happy coding! ❤️