Arrays and Strings

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.

Arrays

What are Arrays?

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.

Declaring Arrays

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

				
			

Initializing Arrays

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

				
			

Accessing Array Elements

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

				
			

Modifying Array Elements

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 Operations

Array Traversal

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

				
			

Searching in Arrays

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

Multi-dimensional arrays are arrays of arrays. They are useful for representing tables, matrices, etc.

Two dimensional Array (2D Array)

Declaration and Initialization

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

				
			

Accessing Elements

				
					printf("%d", matrix[0][0]); // Output: 1

				
			

Traversing 2D array Elements

				
					#include <stdio.h>

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;
}

				
			

Three dimensional Array (3D Array)

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.

Declaration and initialization

				
					int cube[2][3][4];

				
			

Accessing Elements

				
					cube[0][1][2] = 10;

				
			

Traversing Elements

				
					#include <stdio.h>

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]

Strings

What are Strings?

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.

Declaring Strings

Strings in C can be declared as character arrays.

				
					#include <stdio.h>

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

				
			

String Input

You can read strings from the user using scanf() or gets() function.

				
					#include <stdio.h>

int main() {
    char name[20];
    
    printf("Enter your name: ");
    gets(name); // Deprecated, use fgets instead
    
    printf("Hello, %s!\n", name);
    
    return 0;
}

				
			

String Output

Strings can be printed using printf() function with %s format specifier.

				
					#include <stdio.h>

int main() {
    char str1[] = "Unicorn";
    printf("str1: %s\n", str1);
    return 0;
}

				
			

String Functions

String Length

To find the length of a string, you can use the strlen() function from the <string.h> library.

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

int main() {
    char str[] = "Hello";
    int length = strlen(str);
    
    printf("Length of str: %d\n", length);
    
    return 0;
}

				
			
				
					// output //
Length of str: 5
				
			

String Concatenation

Y0ou can concatenate strings using the strcat() function from the <string.h> library.

				
					#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;
}

				
			
				
					// output //
Concatenated string: Hello World
				
			

String Copy

You can copy strings using the strcpy() function from the <string.h> library.

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

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

				
			
				
					// output //
Copied string: Hello
				
			

String Comparison

You can compare strings using the strcmp() function from the <string.h> library.

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

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
				
			

Advanced String Operations

Tokenizing Strings

You can tokenize strings using the strtok() function from the <string.h> library.

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

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
				
			

Searching for Substrings

You can search for substrings within strings using the strstr() function from the <string.h> library.

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

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! ❤️

Table of Contents