Module 3: Chapter 4 — Arrays and Strings

Arrays

Introduction

An array is a collection of similar data elements stored under a single name. These elements all have the same data type and are stored in consecutive memory locations. Each element is identified by a unique index (subscript), which represents its position in the array.

Arrays-in-C

(Arrays-in-C)

Example: A student's marks in 10 subjects can be stored using an integer array instead of creating 10 separate variables.

Declaration of Arrays

Before an array can be used, it must be declared in the program. Declaration reserves memory and defines the type and number of elements the array can hold.

Arrays-Declaration-in-C

(Arrays-Declaration)

Syntax:

type name[size];

When declaring an array, you must specify:

Example:

int marks[10];

This statement declares an integer array named marks that can hold 10 elements. In C, array indices start from 0. Thus:

Note: The index or subscript written inside square brackets [ ] must always be an integer value or an expression that evaluates to an integer.

Array Initialization

When an array is declared or memory is allocated, its elements may contain garbage values. Therefore, it is important to initialize the array with meaningful values.

Examples:

int numbers[] = {1, 2, 3, 4, 5}; // Size inferred from number of elements
int marks[10] = {50, 60, 70}; // First 3 initialized, rest set to 0

Note: Proper initialization ensures that your program does not produce unexpected results due to garbage values in the array.

Arrays-initialization-in-C

(Arrays-Initialization)

Partial-Arrays-initialization-in-C

(Partial-Arrays-Initialization)

array-initialization-with-zero

(Array-Initialization-With-Zero)

Accessing the Elements of an Array

Array elements can be accessed individually using their indices. To process all elements of an array efficiently, loops are typically used.

Example: Setting All Array Elements to -1

int i, marks[10];
for(i = 0; i < 10; i++) {
  marks[i] = -1;
}

In this code:

Remember: Array indices in C always begin at 0 and go up to size - 1. Accessing beyond this range may cause unexpected behavior.

Passing Single-Dimension Arrays to Functions

Definition

In C, an entire array cannot be passed to a function by value. Instead, the base address of the array is passed to the function. This is done by using the array name without any index, which acts as a pointer to the first element of the array.

Syntax

funcName(arrayName);

Explanation

Example

int main() {
  int i[10];
  func1(i);
}

void func1(int *x) {
  /* access array using x */
}

Ways to Receive an Array in a Function

Definition

A function receiving a single-dimension array can declare its parameter in different forms, all of which are treated as a pointer internally.

Syntax

void func(int *x);
void func(int x[10]);
void func(int x[]);

Explanation

Note: Even int x[32] does not create a 32-element array inside the function. Only a pointer is passed.

Strings in C

Definition

A string in C is a one-dimensional array of characters terminated by a null character (\0).

Syntax

char str[size];

Explanation

Example

char str[11] = "HELLO WORLD";
// 10 characters + 1 null character

String Handling Functions (string.h)

Definition

C provides a standard library <string.h> that contains predefined functions to manipulate strings.

Common Functions

strlen() : String Length

Definition

The strlen() function returns the number of characters in a string, excluding the null character.

Syntax

size_t strlen(const char *str);

Explanation

strcpy() : String Copy

Definition

The strcpy() function copies the source string into the destination string, including the null character.

Syntax

char *strcpy(char *dest, const char *src);

Explanation

strcat() : String Concatenation

Definition

The strcat() function appends one string to the end of another.

Syntax

char *strcat(char *str1, const char *str2);

Explanation

strcmp() String Comparison

Definition

The strcmp() function compares two strings lexicographically.

Syntax

int strcmp(const char *str1, const char *str2);

Explanation

Remember, strcmp() returns false if the strings are equal. Be sure to use the logical ! operator to reverse the condition, as just shown, if you are testing for equality

strchr() and strrchr()

Definition

These functions search for a character in a string and return a pointer to its position.

Syntax

char *strchr(const char *str, int c);
char *strrchr(const char *str, int c);

Explanation

Two-Dimensional Arrays

Definition

C supports multidimensional arrays. The simplest form is a two-dimensional array, which can be thought of as an array of one-dimensional arrays arranged in rows and columns.

Syntax

data_type array_name[row_size][column_size];

Example

int d[10][20];

Explanation

Accessing Elements in a Two-Dimensional Array

Definition

Individual elements of a two-dimensional array are accessed using two subscripts: one for the row and one for the column.

Syntax

array_name[row_index][column_index]

Example

d[1][2];

Explanation

Example: Initializing and Printing a Two-Dimensional Array

Program

#include <stdio.h>
int main(void) {
  int t, i, num[3][4];

  for(t = 0; t < 3; ++t)
    for(i = 0; i < 4; ++i)
      num[t][i] = (t * 4) + i + 1;

  for(t = 0; t < 3; ++t) {
    for(i = 0; i < 4; ++i)
      printf("%3d ", num[t][i]);
    printf("\n");
  }
  return 0;
}

Explanation

Memory Representation of Two-Dimensional Arrays

Definition

Two-dimensional arrays are stored in memory using row-major order.

Explanation

Visualization

        1  2  3
        4  5  6
        7  8  9
      

Memory Requirement of Two-Dimensional Arrays

Formula

bytes = rows × columns × sizeof(data_type)

Explanation

Example

For an integer array int a[10][5] with 4-byte integers:

10 x 5 x 4 = 200 bytes

Passing Two-Dimensional Arrays to Functions

Definition

When a two-dimensional array is passed to a function, only a pointer to the first element is passed. The function must know the size of the rightmost dimension.

Syntax

void func(int arr[][columns]);

Example

void func1(int x[][10]) {
  /* function body */
}

Explanation

Example: Matrix Addition Using Two-Dimensional Arrays

Program

#include <stdio.h>
int main() {
  int a[2][2] = {{1,2},{3,4}};
  int b[2][2] = {{5,6},{7,8}};
  int sum[2][2];
  int i, j;

  for(i = 0; i < 2; i++)
    for(j = 0; j < 2; j++)
      sum[i][j] = a[i][j] + b[i][j];

  printf("Sum of matrices:\n");
  for(i = 0; i < 2; i++) {
    for(j = 0; j < 2; j++)
      printf("%d ", sum[i][j]);
    printf("\n");
  }
  return 0;
}


Sum of matrices:5
6 85
10 125

Explanation

Multidimensional Arrays

Definition

C allows the creation of multidimensional arrays, which are arrays with more than one dimension. These arrays extend the concept of one-dimensional and two-dimensional arrays to multiple levels.

Syntax

data_type array_name[size1][size2][size3]...[sizeN];

Explanation