0% found this document useful (0 votes)
4 views49 pages

Unit 4 Arrays

The document provides a comprehensive overview of arrays in C, covering one-dimensional and two-dimensional arrays, their declaration, initialization, and memory representation. It discusses characteristics, applications, limitations, and examples of using arrays, including dynamic memory allocation with functions like malloc and calloc. Additionally, it includes example programs for finding the largest element, reversing an array, and calculating the average of an array.

Uploaded by

nayna sawant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views49 pages

Unit 4 Arrays

The document provides a comprehensive overview of arrays in C, covering one-dimensional and two-dimensional arrays, their declaration, initialization, and memory representation. It discusses characteristics, applications, limitations, and examples of using arrays, including dynamic memory allocation with functions like malloc and calloc. Additionally, it includes example programs for finding the largest element, reversing an array, and calculating the average of an array.

Uploaded by

nayna sawant
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 49

Unit 4 Arrays

Syllabus:

Arrays: One Dimensional Arrays, Declaration of One-dimensional Arrays, Initialization of


One- dimensional Arrays, Two –dimensional Arrays, Initialization of Two- dimensional
Arrays.

Character Arrays and Strings: Declaration and Initialization String Variables, Reading
Strings from Terminal, Writing Strings to Screen, Putting Strings Together, Comparison of
Two Strings, Introduction to String handling Functions

Introduction to Arrays

An array is a collection of variables of the same data type stored in contiguous memory
locations. It allows storing multiple values of the same type in a single data structure and
accessing them using an index.

2. Characteristics of Arrays

 Fixed Size: The size of the array is defined at compile-time and cannot be changed
dynamically (in C).
 Homogeneous Data: All elements of an array must be of the same data type.
 Contiguous Memory: Array elements are stored in adjacent memory locations.
 Indexed Access: Array elements are accessed using an index, which starts from 0.

3. Declaration and Initialization

a. Declaration

data_type array_name[size];

 data_type: Type of data (e.g., int, float, char).


 array_name: Identifier for the array.
 size: Total number of elements the array can hold.

Example:

int numbers[5];
b. Initialization

Arrays can be initialized at the time of declaration or later using loops.

At Declaration:

int numbers[5] = {10, 20, 30, 40, 50};

Partial Initialization: If fewer values are provided, the remaining elements are initialized to
0.

int numbers[5] = {10, 20};

Using Loops:

for(int i = 0; i < 5; i++) {


numbers[i] = i * 10;
}

4. Accessing Array Elements

Array elements are accessed using the index operator [ ].

Example:

printf("%d", numbers[2]); // Accesses the 3rd element

Modifying an Element:

numbers[2] = 25; // Updates the 3rd element to 25

5. Memory Representation

If an integer array numbers[5] is declared, and integers take 4 bytes of memory:

 numbers[0] will be stored at address 0x1000.


 numbers[1] at 0x1004.
 numbers[2] at 0x1008, and so on.

6. Applications of One Dimensional Arrays

1. Storing Data: To store lists of items like marks, temperatures, etc.


2. Searching: Used in linear search or binary search algorithms.
3. Sorting: Arrays are fundamental for sorting algorithms like bubble sort, selection
sort, etc.
4. Mathematical Computations: Arrays are used to implement mathematical
operations such as finding averages, summations, etc.

7. Limitations of Arrays

1. Fixed Size: Cannot change the size after declaration.


2. Static Memory Allocation: Inefficient use of memory if the size is overestimated.
3. No Built-in Bounds Checking: Accessing out-of-bound indices can lead to
undefined behavior.

8. Example Programs

Program to Find the Largest Element

#include <stdio.h>

int main() {
int numbers[5] = {12, 35, 7, 10, 22};
int max = numbers[0];

for(int i = 1; i < 5; i++) {


if(numbers[i] > max) {
max = numbers[i];
}
}

printf("The largest element is: %d\n", max);


return 0;
}

Program to Reverse an Array

#include <stdio.h>

int main() {
int arr[5] = {10, 20, 30, 40, 50};
int size = 5;

printf("Original Array: ");


for(int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}

printf("\nReversed Array: ");


for(int i = size - 1; i >= 0; i--) {
printf("%d ", arr[i]);
}

return 0;
}
One Dimensional Array?

A one-dimensional array is a list of elements, all of the same data type, stored in contiguous
memory locations. Each element is identified by its index or subscript.

Declaration of a One Dimensional Array

data_type array_name[size];

 data_type: Specifies the type of elements (e.g., int, float, char).


 array_name: Name of the array.
 size: Number of elements the array can hold.

Example:

int numbers[5];

Here:

 numbers is the name of the array.


 It can hold up to 5 integer values.

Initialization of One Dimensional Arrays

Arrays can be initialized in two ways:

1. At the time of declaration:

int numbers[5] = {10, 20, 30, 40, 50};

2. Using loops:

int numbers[5];
for(int i = 0; i < 5; i++) {
numbers[i] = i * 10;
}

Accessing and Modifying Array Elements

 Accessing: Use the index to access an element.


Example:

printf("%d", numbers[2]); // Accesses the 3rd element


 Modifying: Assign a new value using the index.
Example:

numbers[2] = 100; // Updates the 3rd element to 100

Example Program: Calculating the Average of an Array

#include <stdio.h>

int main() {
int numbers[5] = {10, 20, 30, 40, 50}; // Array declaration and
initialization
int sum = 0;
float average;

// Calculate the sum of array elements


for(int i = 0; i < 5; i++) {
sum += numbers[i];
}

// Calculate the average


average = (float)sum / 5;

// Display the result


printf("Sum = %d\n", sum);
printf("Average = %.2f\n", average);

return 0;
}

Dynamic declaration of an array in C involves allocating memory at runtime using functions


like malloc, calloc, or realloc. These are provided by the <stdlib.h> library and allow
you to create arrays whose size is determined during program execution.

1. Using malloc

The malloc function allocates memory for an array without initializing its elements.

Syntax:

data_type *array = (data_type *)malloc(size * sizeof(data_type));

 data_type: Type of elements (e.g., int, float).


 size: Number of elements.
 Returns a pointer to the first byte of allocated memory.
Example:

#include <stdio.h>
#include <stdlib.h> // For malloc and free

int main() {
int *array, size;

printf("Enter the size of the array: ");


scanf("%d", &size);

// Allocate memory for the array


array = (int *)malloc(size * sizeof(int));

if (array == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Initialize and display the array


printf("Enter %d elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &array[i]);
}

printf("The array elements are:\n");


for (int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");

// Free allocated memory


free(array);

return 0;
}
Initialization of One-Dimensional Arrays in C

In C, arrays can be initialized either at the time of declaration or after declaration. The
initialization process involves assigning values to the elements of an array, either explicitly or
through loops.

1. Static Initialization at the Time of Declaration

When initializing an array at the time of declaration, you provide a list of values within curly
braces {}. The size of the array can either be explicitly provided or inferred by the compiler
based on the number of elements in the initializer list.

Syntax:

data_type array_name[size] = {value1, value2, ..., valueN};

 data_type: Specifies the type of elements (e.g., int, float).


 array_name: Name of the array.
 size: Optional; if not provided, the compiler will infer it from the number of values.

Example 1:

#include <stdio.h>

int main() {
int numbers[5] = {10, 20, 30, 40, 50}; // Static initialization

// Print the array


for(int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

return 0;
}

Output:

10 20 30 40 50

In this case, the size is explicitly set to 5, and the array elements are initialized with the
values provided.

Example 2:

If you omit the size in the declaration, the compiler will determine the size based on the
number of elements in the initialization list.
#include <stdio.h>

int main() {
int numbers[] = {10, 20, 30, 40, 50}; // Size is inferred by compiler

// Print the array


for(int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

return 0;
}

Output:

10 20 30 40 50

Here, the array size is automatically determined to be 5 based on the number of elements in
the initializer list.

2. Partial Initialization

You can also initialize only part of the array, and the remaining elements will be
automatically set to zero (if the array is of a simple type like int, float, etc.).

Example:

#include <stdio.h>

int main() {
int numbers[5] = {10, 20}; // First two elements initialized, others
set to 0

// Print the array


for(int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

return 0;
}

Output:

10 20 0 0 0

In this case, only the first two elements are explicitly initialized to 10 and 20, while the
remaining three elements are initialized to 0.
3. Initialization Using a Loop

If you don't know the values of the array elements at the time of declaration, you can
initialize the array using a loop after declaring it.

Example:

#include <stdio.h>

int main() {
int numbers[5];

// Initialize array using a loop


for (int i = 0; i < 5; i++) {
numbers[i] = (i + 1) * 10; // Initialize with multiples of 10
}

// Print the array


for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

return 0;
}

Output:

10 20 30 40 50

In this example, a loop is used to initialize the array with multiples of 10.

4. Initializing Array of Strings (Character Arrays)

Character arrays (strings) are initialized similarly to other arrays, but each element is a single
character.

Example:

#include <stdio.h>

int main() {
char names[3][10] = {"John", "Alice", "Bob"}; // Array of strings

// Print the array


for (int i = 0; i < 3; i++) {
printf("%s\n", names[i]);
}

return 0;
}
5. Omitting Array Size During Initialization in C

When you initialize an array in C without specifying the size, the compiler automatically
determines the size of the array based on the number of elements in the initializer list.

Syntax for Omitting Array Size


data_type array_name[] = {value1, value2, ..., valueN};

 data_type: Specifies the type of the elements (e.g., int, float, etc.).
 array_name: Name of the array.
 value1, value2, ..., valueN: The elements used to initialize the array.

When the size is omitted, the compiler counts the number of elements in the initializer list
and assigns the appropriate size to the array.

Example 1: Initializing an Array with Omitting Size

#include <stdio.h>

int main() {
int numbers[] = {10, 20, 30, 40, 50}; // Size is omitted

// Print the array


for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}

return 0;
}

Output:

10 20 30 40 50
Dynamic Initialization of Arrays in C

Dynamic initialization refers to the process of assigning values to array elements at runtime,
rather than at compile time. This can be done using loops or functions like malloc, calloc,
or realloc, which allow for dynamic memory allocation and manipulation of arrays.

Here, we'll cover two aspects of dynamic initialization in C:

1. Using Loops for Dynamic Initialization


2. Using Dynamic Memory Allocation (malloc, calloc, realloc)

1. Dynamic Initialization Using Loops

In dynamic initialization, you assign values to the elements of an array during the program
execution, usually in a loop. This can be useful when the size of the array is not known at
compile time, or when values are generated or read from external sources (e.g., user input,
files, etc.).

Example 1: Initializing an Array Using a Loop

#include <stdio.h>

int main() {
int n;

// Take input for the size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Declare the array with dynamic size


int numbers[n];

// Initialize the array elements dynamically using a loop


for (int i = 0; i < n; i++) {
numbers[i] = (i + 1) * 10; // Assign multiples of 10
}

// Print the array


printf("The array elements are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}

return 0;
}

Output:

Enter the size of the array: 5


The array elements are:
10 20 30 40 50
2. Dynamic Initialization Using Dynamic Memory Allocation

C provides several functions to allocate memory dynamically during runtime. These


functions are provided by the stdlib.h library and are used to create arrays whose sizes are
determined during execution.

a. Using malloc for Dynamic Memory Allocation

The malloc (memory allocation) function is used to allocate a block of memory of a


specified size. It does not initialize the memory, leaving it with random values.

Syntax:

data_type *array = (data_type *)malloc(size * sizeof(data_type));

 data_type: Specifies the type of the elements (e.g., int, float).


 size: The number of elements to be allocated.
 Returns a pointer to the allocated memory.

Example: Using malloc for Dynamic Initialization

#include <stdio.h>
#include <stdlib.h>

int main() {
int *numbers;
int n;

// Take input for the size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Dynamically allocate memory for the array


numbers = (int *)malloc(n * sizeof(int));

if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Initialize the array elements dynamically


for (int i = 0; i < n; i++) {
numbers[i] = (i + 1) * 10; // Assign multiples of 10
}

// Print the array


printf("The array elements are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}

// Free the allocated memory


free(numbers);

return 0;
}
Output:

Enter the size of the array: 5


The array elements are:
10 20 30 40 50

b. Using calloc for Dynamic Memory Allocation

The calloc (contiguous allocation) function is similar to malloc but additionally initializes
the memory to zero.

Syntax:

data_type *array = (data_type *)calloc(size, sizeof(data_type));

 size: The number of elements.


 sizeof(data_type): The size of one element.
 Initializes the memory to zero.

Example: Using calloc for Dynamic Initialization

#include <stdio.h>
#include <stdlib.h>

int main() {
int *numbers;
int n;

// Take input for the size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Dynamically allocate memory and initialize it to zero


numbers = (int *)calloc(n, sizeof(int));

if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Initialize the array elements dynamically


for (int i = 0; i < n; i++) {
numbers[i] = (i + 1) * 10; // Assign multiples of 10
}

// Print the array


printf("The array elements are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}

// Free the allocated memory


free(numbers);

return 0;
}

Output:

Enter the size of the array: 5


The array elements are:
10 20 30 40 50

Here, the calloc function allocates memory and initializes it to 0, but we still modify the
elements in the loop after allocation.

c. Using realloc to Resize an Array

The realloc function is used to resize an already allocated block of memory, either
increasing or decreasing the size.

Syntax:

array = (data_type *)realloc(array, new_size * sizeof(data_type));

 new_size: The new size for the array.


 Returns a pointer to the resized memory block.

Example: Using realloc for Dynamic Initialization

#include <stdio.h>
#include <stdlib.h>

int main() {
int *numbers;
int n;

// Take input for the initial size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Dynamically allocate memory for the initial array


numbers = (int *)malloc(n * sizeof(int));

if (numbers == NULL) {
printf("Memory allocation failed!\n");
return 1;
}

// Initialize the array elements


for (int i = 0; i < n; i++) {
numbers[i] = (i + 1) * 10; // Assign multiples of 10
}
// Resize the array using realloc
printf("Enter the new size of the array: ");
scanf("%d", &n);
numbers = (int *)realloc(numbers, n * sizeof(int));

if (numbers == NULL) {
printf("Memory reallocation failed!\n");
return 1;
}

// Print the resized array


printf("The updated array elements are:\n");
for (int i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}

// Free the allocated memory


free(numbers);

return 0;
}

Output:

Enter the size of the array: 5


Enter the new size of the array: 8
The updated array elements are:
10 20 30 40 50 0 0 0

Program to Demonstrate One-Dimensional Array

#include <stdio.h>

int main() {
int n;

// Input the size of the array


printf("Enter the size of the array: ");
scanf("%d", &n);

// Declare an array of size 'n'


int numbers[n];

// Dynamic Initialization of the array using a loop


printf("Enter %d elements for the array:\n", n);
for (int i = 0; i < n; i++) {
printf("Element %d: ", i + 1);
scanf("%d", &numbers[i]);
}

// Display the elements of the array


printf("\nThe elements of the array are:\n");
for (int i = 0; i < n; i++) {
printf("Element %d: %d\n", i + 1, numbers[i]);
}
// Accessing an individual element by index
int index;
printf("\nEnter the index to access an element (0 to %d): ", n - 1);
scanf("%d", &index);

if (index >= 0 && index < n) {


printf("Element at index %d is: %d\n", index, numbers[index]);
} else {
printf("Invalid index!\n");
}

return 0;
}

Two-Dimensional Arrays in C

A Two-Dimensional Array (also known as a matrix) is an array of arrays. It can be


visualized as a table with rows and columns. Each element in a two-dimensional array is
accessed using two indices: one for the row and one for the column.

Syntax for Declaring a Two-Dimensional Array

data_type array_name[row_size][column_size];

 data_type: Specifies the type of the elements (e.g., int, float).


 array_name: Name of the array.
 row_size: The number of rows.
 column_size: The number of columns.

Example of Declaring a Two-Dimensional Array

int matrix[3][4]; // A matrix with 3 rows and 4 columns

In this example, matrix is a two-dimensional array with 3 rows and 4 columns.

Initialization of Two-Dimensional Arrays

There are several ways to initialize a two-dimensional array in C.

1. Static Initialization (at Declaration)


You can initialize a two-dimensional array at the time of declaration using curly braces {}.
You can either initialize all elements or part of the array. The uninitialized elements are
automatically set to zero.

Syntax for Static Initialization

data_type array_name[row_size][column_size] = { {value1, value2, ...,


valueN}, {value1, value2, ..., valueN}, ... };

Example 1: Fully Initializing a Two-Dimensional Array

#include <stdio.h>

int main() {
// Initialize a 3x3 matrix
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Display the matrix


printf("The matrix is:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}

return 0;
}

Output:

The matrix is:


1 2 3
4 5 6
7 8 9

In this example, a 3x3 matrix is initialized with values, and each element is accessed using
two indices matrix[i][j].

2. Partial Initialization (at Declaration)

If fewer values are provided than the number of elements in the array, the remaining elements
are automatically initialized to 0.

Example 2: Partially Initializing a Two-Dimensional Array


#include <stdio.h>

int main() {
// Partially initialize a 3x3 matrix
int matrix[3][3] = {
{1, 2}, // First row with two elements
{4, 5, 6}, // Second row with three elements
{7} // Third row with one element
};

// Display the matrix


printf("The matrix is:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}

return 0;
}

Output:

The matrix is:


1 2 0
4 5 6
7 0 0

In this example, elements not initialized are set to 0 automatically.

3. Initializing with Nested Loops

You can also use loops to initialize a two-dimensional array dynamically, particularly useful
when you don't know the values in advance.

Example 3: Initializing with Nested Loops

#include <stdio.h>

int main() {
int matrix[3][3]; // Declare a 3x3 matrix

// Initialize the matrix dynamically using nested loops


printf("Enter the elements for a 3x3 matrix:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("Element[%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}

// Display the matrix


printf("\nThe matrix is:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}

return 0;
}

Output:

Enter the elements for a 3x3 matrix:


Element[0][0]: 1
Element[0][1]: 2
Element[0][2]: 3
Element[1][0]: 4
Element[1][1]: 5
Element[1][2]: 6
Element[2][0]: 7
Element[2][1]: 8
Element[2][2]: 9

The matrix is:


1 2 3
4 5 6
7 8 9

This approach allows you to enter elements at runtime, providing more flexibility.

4. Omitting the Column Size (For Initialization)

When initializing a two-dimensional array, you can omit the column size, and the compiler
will calculate it based on the number of values in the initializer list.

Example 4: Omitting the Column Size

#include <stdio.h>

int main() {
// Initialize a 2D array where column size is omitted
int matrix[][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Display the matrix


printf("The matrix is:\n");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}

return 0;
}

Output:

The matrix is:


1 2 3
4 5 6
7 8 9

C Program Demonstrating Two-Dimensional Array

#include <stdio.h>

int main() {
// Declare and initialize a 2x3 matrix
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};

// Display the elements of the matrix


printf("The 2D Matrix is:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}

// Accessing individual elements in the matrix


int row, col;
printf("\nEnter row and column to access an element (row 0-1, column 0-
2): ");
scanf("%d %d", &row, &col);

// Checking if the indices are valid


if (row >= 0 && row < 2 && col >= 0 && col < 3) {
printf("Element at position (%d, %d) is: %d\n", row, col,
matrix[row][col]);
} else {
printf("Invalid indices!\n");
}

return 0;
}

Explanation:

1. Matrix Declaration and Initialization:


o The matrix matrix[2][3] is declared with 2 rows and 3 columns.
o It is initialized with the values { {1, 2, 3}, {4, 5, 6} }.
2. Displaying the Matrix:
o A nested for loop is used to iterate through the rows and columns of the matrix
and print each element.
3. Accessing an Element:
o The user is prompted to enter a row and column index to access a specific element
in the matrix.
o The program checks if the input indices are valid (i.e., within the array bounds) and
then prints the corresponding matrix element.

Sample Output:

The 2D Matrix is:


1 2 3
4 5 6

Enter row and column to access an element (row 0-1, column 0-2): 1 2
Element at position (1, 2) is: 6

Character Arrays and Strings in C

In C, a string is a sequence of characters stored in an array. A character array is used to


store the individual characters, and the sequence of characters is terminated with a special
null character '\0', which marks the end of the string.

Character Arrays

A Character Array is simply an array of char type, and it is commonly used to store strings.
Each element of the array holds a single character.

Syntax for Declaring a Character Array:

char array_name[size];

 array_name: Name of the array.


 size: The number of characters the array can hold, including the null character ('\0').

String Variables in C

A String is a sequence of characters, and in C, strings are represented as character arrays.


The string's last element must be the null character ( '\0'), which indicates the end of the
string.
Declaration of Character Arrays

You can declare a character array in C by specifying the size of the array or using a string
literal for initialization.

1. Declaring a Character Array Without Initialization

char name[20]; // Declare a character array of size 20

This creates an array of 20 characters, which can store a string of up to 19 characters, as the
last character will be reserved for the null character ( '\0').

2. Declaring and Initializing a Character Array

You can initialize a character array either with individual characters or using a string literal.

a. Using Individual Characters:

char name[5] = {'J', 'o', 'h', 'n', '\0'};

This creates an array of characters representing the string "John".

b. Using a String Literal:

char name[] = "John"; // The size is implicitly determined to be 5 (4


characters + '\0')

Here, the compiler automatically adds the null character '\0' at the end of the string, and the
array will be of size 5.

Initialization of String Variables

When you initialize a string, it is important to include the null character '\0', which tells the
program where the string ends.

Example of String Initialization:

#include <stdio.h>

int main() {
// String initialization using a string literal
char greeting[] = "Hello, World!";

// Displaying the string


printf("The greeting message is: %s\n", greeting);
return 0;
}

Here, the string greeting is initialized with the value "Hello, World!". The array
greeting[] is automatically sized to hold 14 characters (13 characters + '\0').

Example 1: Declaring and Initializing a Character Array Using Individual Characters

#include <stdio.h>

int main() {
// Declare and initialize a character array with individual characters
char name[5] = {'J', 'o', 'h', 'n', '\0'}; // Null character is added
manually

// Display the string


printf("Name: %s\n", name); // %s prints the string

return 0;
}

Output:

Name: John

 Explanation: The array name is explicitly initialized with the characters 'J', 'o', 'h', 'n',
followed by the null character '\0' to mark the end of the string. When the string is printed
using %s, it correctly displays "John".

Example 2: Declaring and Initializing a Character Array Using a String Literal

#include <stdio.h>

int main() {
// Declare and initialize a character array with a string literal
char greeting[] = "Hello, World!";

// Display the string


printf("Greeting: %s\n", greeting); // %s prints the string

return 0;
}

Output:

Greeting: Hello, World!


 Explanation: In this example, the array greeting[] is initialized with the string literal
"Hello, World!". The compiler automatically adds the null character '\0' at the end of
the string.

Example 3: Declaring a Character Array Without Initialization

#include <stdio.h>

int main() {
// Declare a character array without initialization
char name[20];

// Initialize the array manually


name[0] = 'A';
name[1] = 'l';
name[2] = 'i';
name[3] = 'c';
name[4] = 'e';
name[5] = '\0'; // Null character to terminate the string

// Display the string


printf("Name: %s\n", name); // %s prints the string

return 0;
}

Output:

Name: Alice

 Explanation: In this example, the character array name is declared without initialization. The
individual characters are assigned to the array manually, and the null character '\0' is
added at the end to terminate the string properly.

Example 4: Using a Character Array to Input a String from the User

#include <stdio.h>

int main() {
char name[30]; // Declare a character array to hold the string

// Prompt the user to input their name


printf("Enter your name: ");
scanf("%s", name); // Input the string (no spaces allowed)

// Display the string entered by the user


printf("Your name is: %s\n", name);

return 0;
}

Output (Example):

Enter your name: John


Your name is: John

 Explanation: The program uses scanf("%s", name) to read a string input from the user
and stores it in the name array. The string will be terminated automatically by the null
character when entered.

Reading Strings from Terminal in C

In C, there are several ways to read strings from the terminal (input) provided by the user.
The most common methods are scanf(), fgets(), and getchar(). Each method has its
advantages and limitations, especially when dealing with strings that contain spaces.

1. Using scanf()

The scanf() function is used to read input from the terminal. However, by default, scanf()
only reads a string up to the first whitespace (spaces, tabs, or newlines). This means it doesn't
handle strings with spaces very well.

Syntax:

scanf("%s", string_variable);

 %s reads a string until the first whitespace is encountered.


 The string variable must be a character array.

Example:

#include <stdio.h>

int main() {
char name[30]; // Declare a character array to hold the string

// Prompt the user to input their name


printf("Enter your name: ");
scanf("%s", name); // Read a string (stops at space)

// Display the string entered by the user


printf("Your name is: %s\n", name);

return 0;
}
Output:

Enter your name: John


Your name is: John

Limitation:

 If the user enters a name with spaces (e.g., "John Doe"), scanf() will only read the first
word ("John") and stop at the first space.

2. Using fgets()

The fgets() function is more flexible than scanf() because it can read strings with spaces
and includes the newline character (\n) at the end of the input.

Syntax:

fgets(string_variable, size_of_string, stdin);

 string_variable: The character array where the string will be stored.


 size_of_string: The maximum number of characters to be read.
 stdin: Standard input stream (keyboard).

Example:

#include <stdio.h>

int main() {
char name[50]; // Declare a character array to hold the string

// Prompt the user to input their full name


printf("Enter your full name: ");
fgets(name, sizeof(name), stdin); // Read string with spaces

// Display the string entered by the user


printf("Your name is: %s\n", name);

return 0;
}

Output:

Enter your full name: John Doe


Your name is: John Doe

Advantages of fgets():

 It reads the entire line of input, including spaces.


 You can specify the maximum number of characters to be read, preventing buffer overflow.

Limitation:

 fgets() includes the newline character '\n' when the user presses Enter. This can be
removed by manually replacing the newline character if needed.

name[strcspn(name, "\n")] = '\0'; // Remove newline character

3. Using getchar()

The getchar() function reads a single character at a time, so you can use it to read a string
character by character. You need a loop to read multiple characters and store them in a
character array.

Syntax:

ch = getchar();

 ch: A variable that stores the character returned by getchar().


 getchar() returns one character at a time, including spaces, until a newline (\n) is
encountered.

Example:

#include <stdio.h>

int main() {
char name[50]; // Declare a character array to hold the string
int i = 0;
char ch;

// Prompt the user to input their name


printf("Enter your name: ");

// Use getchar() to read the name character by character


while ((ch = getchar()) != '\n' && ch != EOF) {
name[i] = ch;
i++;
}
name[i] = '\0'; // Null-terminate the string

// Display the string entered by the user


printf("Your name is: %s\n", name);

return 0;
}

Output:
Enter your name: John Doe
Your name is: John Doe

Advantages of getchar():

 It reads each character, so it can handle spaces and any character input.
 You can easily control the input loop to manage the string format.

Summary of Methods for Reading Strings:


Handles Stops at First
Method Handles Newline Input Limitations
Spaces Space

scanf() No Yes No Stops at whitespace

Yes (includes You need to remove newline


fgets() Yes No
newline) manually if needed

Yes (if used in a


getchar() Yes No Needs a loop for multiple characters
loop)

Writing Strings to the Screen in C

In C, strings can be written to the screen (or standard output) using various methods. The
most commonly used functions are printf(), puts(), and fputs().

1. Using printf() to Write Strings

The printf() function is one of the most versatile and widely used functions in C for output.
It allows formatted output, meaning you can specify how the string should be displayed.

Syntax:

printf("format_specifier", string_variable);

 "format_specifier": The format string that specifies how the data should be displayed
(e.g., %s for strings).
 string_variable: The variable or string literal to be printed.

Example:
#include <stdio.h>

int main() {
char greeting[] = "Hello, World!"; // Declare and initialize a string

// Use printf to write the string to the screen


printf("The greeting message is: %s\n", greeting);

return 0;
}

Output:

The greeting message is: Hello, World!

 Explanation: The %s format specifier tells printf() to output the string. The string
greeting is printed on the screen.

2. Using puts() to Write Strings

The puts() function is a simpler alternative to printf() for printing strings. It automatically
appends a newline (\n) at the end of the string.

Syntax:

puts(string_variable);

 string_variable: The string to be printed.

Example:

#include <stdio.h>

int main() {
char greeting[] = "Hello, World!"; // Declare and initialize a string

// Use puts to write the string to the screen


puts(greeting);

return 0;
}

Output:

Hello, World!

 Explanation: The puts() function prints the string followed by a newline. You don’t need to
manually include \n, as puts() does it for you.
3. Using fputs() to Write Strings

The fputs() function is similar to puts(), but it does not append a newline character at the
end. It is often used when you need more control over the output format, especially when you
want to direct the output to a specific file or stream.

Syntax:

fputs(string_variable, stream);

 string_variable: The string to be printed.


 stream: The output stream (e.g., stdout for the screen, or a file pointer).

Example:

#include <stdio.h>

int main() {
char greeting[] = "Hello, World!"; // Declare and initialize a string

// Use fputs to write the string to the screen


fputs(greeting, stdout);

return 0;
}

Output:

Hello, World!

 Explanation: fputs() writes the string directly to the specified stream (stdout in this case,
which refers to the screen). Unlike puts(), it does not add a newline automatically.

Summary of String Output Functions


Function Description Automatically Adds Newline

printf() Prints formatted output, very flexible No

puts() Prints a string followed by a newline Yes

fputs() Prints a string without newline No


Putting Strings Together in C (Concatenation)

In C, you can combine or concatenate strings using different methods. The most common
ways are using the strcat() function from the C standard library, and manual character-by-
character manipulation. Below are the various ways to put strings together:

1. Using strcat() for String Concatenation

The strcat() function from the <string.h> library is specifically designed for
concatenating (joining) two strings. It appends the contents of one string to the end of another
string.

Syntax:

strcat(destination_string, source_string);

 destination_string: The string to which another string will be appended.


 source_string: The string that will be appended to the destination_string.

Example:

#include <stdio.h>
#include <string.h> // Include the string.h library for strcat()

int main() {
char str1[50] = "Hello, "; // Initialize str1 with a string
char str2[] = "World!"; // Initialize str2 with a string

// Concatenate str2 to str1


strcat(str1, str2);

// Display the concatenated string


printf("Concatenated string: %s\n", str1);

return 0;
}

Output:

Concatenated string: Hello, World!

 Explanation: The function strcat() appends str2 to the end of str1. After the
concatenation, str1 contains the combined string.

Important Notes:

 Ensure that the destination_string (in this case, str1) has enough space to hold the
concatenated result. If the destination array is too small, it may lead to a buffer overflow.
 Always leave extra space in the destination string for the combined content and the null
terminator ('\0').

2. Using sprintf() for Concatenation with Formatting

The sprintf() function is often used for more complex concatenation or when you need to
format strings as you combine them.

Syntax:

sprintf(destination_string, "format_specifier", string1, string2, ...);

 destination_string: The string where the formatted output will be stored.


 "format_specifier": A format string that determines how the output should look.

Example:

#include <stdio.h>

int main() {
char str1[] = "Hello, ";
char str2[] = "World!";
char result[50]; // Declare an array to store the concatenated result

// Use sprintf to concatenate with formatting


sprintf(result, "%s%s", str1, str2);

// Display the concatenated string


printf("Concatenated string: %s\n", result);

return 0;
}

Output:

Concatenated string: Hello, World!

 Explanation: sprintf() is used to combine str1 and str2 into the result array. It uses
the format "%s%s" to specify that both strings should be concatenated.

Advantages:

 You can format the strings or add additional text during concatenation (e.g., numbers,
special characters).
 You can specify a destination array where the formatted string will be placed.
3. Manual Concatenation Using a Loop

If you want more control over the concatenation process, you can manually append each
character from one string to another using a loop.

Example:

#include <stdio.h>

int main() {
char str1[50] = "Hello, ";
char str2[] = "World!";
int i = 0, j = 0;

// Move to the end of str1


while (str1[i] != '\0') {
i++;
}

// Append str2 to str1 character by character


while (str2[j] != '\0') {
str1[i] = str2[j];
i++;
j++;
}

// Null-terminate the resulting string


str1[i] = '\0';

// Display the concatenated string


printf("Concatenated string: %s\n", str1);

return 0;
}

Output:

Concatenated string: Hello, World!

 Explanation: This code manually appends each character from str2 to str1 using two
while loops. After the loop completes, the str1 array holds the concatenated result.
Finally, we ensure that the concatenated string is null-terminated by adding '\0'.

4. Using + Operator for String Literals (in C++)

Although C does not support the + operator for string concatenation (unlike languages like
Python or JavaScript), C++ does support it with std::string. However, in C, we use
functions like strcat() or sprintf() to concatenate strings.
Summary of Methods to Concatenate Strings in C:
Method Description Limitation

Requires enough space in the


strcat() Appends one string to another.
destination array.

Offers more flexibility for complex


sprintf() Formats and concatenates strings.
formatting.

Manual Manually appends each character from one Gives complete control, but requires
Loop string to another. more code.

Comparison of Two Strings in C

In C, comparing two strings involves determining whether they are identical or whether one
is lexicographically greater than the other. There are two primary methods to compare
strings:

1. Using the strcmp() function from the standard library.


2. Manual comparison using loops to compare the strings character by character.

Let's explore both methods in detail.

1. Using strcmp() Function

The strcmp() function from the <string.h> library is used to compare two strings
lexicographically. It compares the strings character by character and returns an integer value
based on the comparison.

Syntax:

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

 str1: The first string to be compared.


 str2: The second string to be compared.

Return Value:

 0: If the strings are equal (both strings are identical).


 Negative value: If str1 is lexicographically less than str2 (i.e., str1 comes before str2 in
dictionary order).
 Positive value: If str1 is lexicographically greater than str2 (i.e., str1 comes after str2 in
dictionary order).

Example:

#include <stdio.h>
#include <string.h> // Include string.h for strcmp

int main() {
char str1[] = "apple";
char str2[] = "banana";
char str3[] = "apple";

// Comparing str1 and str2


int result1 = strcmp(str1, str2);
if (result1 == 0)
printf("str1 and str2 are equal.\n");
else if (result1 < 0)
printf("str1 is lexicographically less than str2.\n");
else
printf("str1 is lexicographically greater than str2.\n");

// Comparing str1 and str3


int result2 = strcmp(str1, str3);
if (result2 == 0)
printf("str1 and str3 are equal.\n");
else if (result2 < 0)
printf("str1 is lexicographically less than str3.\n");
else
printf("str1 is lexicographically greater than str3.\n");

return 0;
}

Output:

str1 is lexicographically less than str2.


str1 and str3 are equal.

 Explanation:
o The first comparison checks if "apple" is lexicographically less than "banana",
which is true.
o The second comparison checks if "apple" is equal to "apple", which is true.

2. Manual Comparison Using Loops

If you prefer, or need, to compare strings manually (for example, when you're implementing
your own string comparison function), you can do so by iterating through each character in
the strings and comparing them one by one.

Logic:
1. Compare characters at the same position in both strings.
2. If the characters are different, the strings are not equal, and you can stop the comparison.
3. If all characters are the same but the lengths of the strings are different, then the shorter
string is considered smaller.
4. If all characters match and the strings end at the same point (i.e., both are terminated by the
null character \0), then the strings are equal.

Example:

#include <stdio.h>

int compareStrings(char str1[], char str2[]) {


int i = 0;

// Compare each character until the null terminator is reached


while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
return 0; // Strings are not equal
}
i++;
}

// If both strings ended, they are equal


// If one string ended and the other didn't, they are not equal
if (str1[i] == str2[i]) {
return 1; // Strings are equal
} else {
return 0; // Strings are not equal
}
}

int main() {
char str1[] = "Hello";
char str2[] = "Hello";
char str3[] = "hello";

if (compareStrings(str1, str2)) {
printf("str1 and str2 are equal.\n");
} else {
printf("str1 and str2 are not equal.\n");
}

if (compareStrings(str1, str3)) {
printf("str1 and str3 are equal.\n");
} else {
printf("str1 and str3 are not equal.\n");
}

return 0;
}

Output:

str1 and str2 are equal.


str1 and str3 are not equal.
 Explanation:
o In the first comparison, str1 and str2 are identical, so the function returns 1 (true)
and prints that the strings are equal.
o In the second comparison, str1 and str3 differ by the case of the first letter ('H'
vs. 'h'), so the function returns 0 (false) and prints that the strings are not equal.

Key Points of Manual Comparison:

 Null Terminator ('\0'): It is important to check for the null terminator to prevent accessing
memory outside the string bounds.
 Case Sensitivity: By default, the manual comparison is case-sensitive, just like strcmp(). If
you want a case-insensitive comparison, you would need to convert both strings to
lowercase (or uppercase) before comparing.

3. Comparison Logic Summary

 Using strcmp():
o Pros: Simple and concise.
o Cons: Case-sensitive by default, but can be modified using strcasecmp() for case-
insensitive comparison.
 Manual Comparison:
o Pros: Gives you complete control over the comparison process, allowing for custom
logic (e.g., case-insensitivity or ignoring certain characters).
o Cons: More code to write and maintain.

Case-Insensitive Comparison Using strcasecmp()

If you need to compare two strings without considering case sensitivity, you can use the
strcasecmp() function (available in POSIX-compliant systems, but not in the C standard
library).

Syntax:

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

 It works like strcmp(), but it ignores case differences.


Summary of String Comparison
Method Function Description Return Value

Compares two strings 0 (equal), Negative (str1 <


Standard strcmp()
lexicographically. str2), Positive (str1 > str2)

Compares two strings manually,


Manual Custom Loop 1 (equal), 0 (not equal)
character by character.

Case- Compares two strings 0 (equal), Negative (str1 <


strcasecmp()
insensitive lexicographically, ignoring case. str2), Positive (str1 > str2)

Introduction to String Handling Functions in C

In C, strings are arrays of characters terminated by a special null character ( '\0'). C provides
a range of built-in functions for handling strings, which are included in the <string.h>
library. These functions allow you to manipulate and process strings easily. Below, we'll
introduce the most commonly used string handling functions, categorized by their
functionality.

1. String Copying Functions

strcpy() — Copy a String

The strcpy() function copies the contents of one string to another. The destination string
must be large enough to hold the copied string, including the null terminator ( '\0').

Syntax:

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

 dest: The destination string where the source string will be copied.
 src: The source string that will be copied.

Example:

#include <stdio.h>
#include <string.h>
int main() {
char src[] = "Hello, World!";
char dest[50];

strcpy(dest, src); // Copy src into dest

printf("Source: %s\n", src);


printf("Destination: %s\n", dest);

return 0;
}

Output:

Source: Hello, World!


Destination: Hello, World!

2. String Concatenation Functions

strcat() — Concatenate Two Strings

The strcat() function appends the content of one string (source) to another string
(destination). The destination string must be large enough to hold both strings.

Syntax:

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

 dest: The destination string to which the source string will be appended.
 src: The source string that will be appended to dest.

Example:

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

int main() {
char str1[50] = "Hello, ";
char str2[] = "World!";

strcat(str1, str2); // Append str2 to str1

printf("Concatenated String: %s\n", str1);

return 0;
}

Output:

Concatenated String: Hello, World!


3. String Length Functions

strlen() — Calculate the Length of a String

The strlen() function calculates the length of a string by counting the number of characters
before the null terminator ('\0').

Syntax:

size_t strlen(const char *str);

 str: The string whose length you want to determine.

Example:

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

int main() {
char str[] = "Hello, World!";
int length = strlen(str); // Find the length of str

printf("Length of string: %d\n", length);

return 0;
}

Output:

Length of string: 13

4. String Comparison Functions

strcmp() — Compare Two Strings

The strcmp() function compares two strings lexicographically (character by character).

Syntax:

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

 str1: The first string to be compared.


 str2: The second string to be compared.

Return Values:
 0: If the strings are equal.
 A negative integer: If str1 is lexicographically less than str2.
 A positive integer: If str1 is lexicographically greater than str2.

Example:

#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.

5. String Search Functions

strchr() — Search for a Character in a String

The strchr() function searches for the first occurrence of a specified character in a string.

Syntax:

char *strchr(const char *str, int ch);

 str: The string in which the character will be searched.


 ch: The character to be searched.

Example:

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

int main() {
char str[] = "Hello, World!";
char *ptr = strchr(str, 'o'); // Find first occurrence of 'o'
if (ptr != NULL) {
printf("Character found at position: %ld\n", ptr - str);
} else {
printf("Character not found.\n");
}

return 0;
}

Output:

Character found at position: 4

strstr() — Search for a Substring in a String

The strstr() function finds the first occurrence of a substring in a string.

Syntax:

char *strstr(const char *haystack, const char *needle);

 haystack: The string to be searched.


 needle: The substring to search for in haystack.

Example:

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

int main() {
char str[] = "Hello, World!";
char *result = strstr(str, "World"); // Search for "World" in str

if (result != NULL) {
printf("Substring found: %s\n", result);
} else {
printf("Substring not found.\n");
}

return 0;
}

Output:

Substring found: World!


6. String Tokenization Functions

strtok() — Tokenize a String

The strtok() function splits a string into tokens based on a delimiter (such as spaces or
commas).

Syntax:

char *strtok(char *str, const char *delim);

 str: The string to be tokenized. On subsequent calls, this parameter should be NULL.
 delim: A string containing delimiter characters.

Example:

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

int main() {
char str[] = "C is a powerful language!";
char *token = strtok(str, " "); // Split by spaces

while (token != NULL) {


printf("Token: %s\n", token);
token = strtok(NULL, " ");
}

return 0;
}

Output:

Token: C
Token: is
Token: a
Token: powerful
Token: language!

7. String Case Conversion Functions

strupr() (Non-Standard) — Convert to Uppercase

Converts all characters of a string to uppercase.

Example:

#include <stdio.h>
#include <string.h>
int main() {
char str[] = "hello world!";
strupr(str); // Convert string to uppercase

printf("Uppercase: %s\n", str);


return 0;
}

Output:

Uppercase: HELLO WORLD!

strlwr() (Non-Standard) — Convert to Lowercase

Converts all characters of a string to lowercase.

Example:

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

int main() {
char str[] = "HELLO WORLD!";
strlwr(str); // Convert string to lowercase

printf("Lowercase: %s\n", str);


return 0;
}

Output:

Lowercase: hello world!

Here’s a complete demonstration of various string handling functions in C, including


strcpy(), strcat(), strlen(), strcmp(), and strstr():

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

int main() {
// 1. Demonstration of strcpy() - Copying a string
char source[] = "Hello, C programming!";
char destination[50];

strcpy(destination, source); // Copy content of source into


destination
printf("Copied String (using strcpy): %s\n", destination);

// 2. Demonstration of strcat() - Concatenating two strings


char str1[50] = "Hello, ";
char str2[] = "world!";

strcat(str1, str2); // Append str2 to str1


printf("Concatenated String (using strcat): %s\n", str1);

// 3. Demonstration of strlen() - Finding length of a string


int length = strlen(source); // Get the length of the source string
printf("Length of the string (using strlen): %d\n", length);

// 4. Demonstration of strcmp() - Comparing two strings


char str3[] = "apple";
char str4[] = "banana";
int result = strcmp(str3, str4); // Compare str3 with str4

if(result == 0) {
printf("Strings are equal (using strcmp).\n");
} else if(result < 0) {
printf("String str3 is lexicographically less than str4 (using
strcmp).\n");
} else {
printf("String str3 is lexicographically greater than str4 (using
strcmp).\n");
}

// 5. Demonstration of strstr() - Searching for a substring


char *found = strstr(source, "C");

if (found != NULL) {
printf("Substring found: %s\n", found); // Substring starting from
"C"
} else {
printf("Substring not found.\n");
}

// 6. Demonstration of strtok() - Tokenizing a string


char str5[] = "C programming is fun";
char *token = strtok(str5, " "); // Split string by spaces

while (token != NULL) {


printf("Token: %s\n", token); // Print each token
token = strtok(NULL, " "); // Continue tokenizing
}

return 0;
}

Explanation of Each Function:

1. strcpy(): Copies the content of source string into destination. In this example,
the string "Hello, C programming!" is copied to destination.
o Output: "Copied String (using strcpy): Hello, C programming!"
2. strcat(): Appends the string str2 ("world!") to str1 ("Hello, "). After
concatenation, str1 will contain "Hello, world!".
o Output: "Concatenated String (using strcat): Hello, world!"
3. strlen(): Calculates and returns the length of the string source ("Hello, C
programming!"). The length excludes the null terminator.
o Output: "Length of the string (using strlen): 23"
4. strcmp(): Compares two strings, str3 ("apple") and str4 ("banana"). It returns:
o 0 if both strings are equal.
o A negative value if the first string is lexicographically smaller.
o A positive value if the first string is lexicographically larger.
o In this case, "apple" is lexicographically smaller than "banana", so the output will
indicate that.
o Output: "String str3 is lexicographically less than str4 (using
strcmp)."
5. strstr(): Searches for the first occurrence of a substring ("C") within a string
(source). It returns a pointer to the first character of the found substring or NULL if the
substring is not found.
o Output: "Substring found: C programming!"
6. strtok(): Tokenizes the string str5 ("C programming is fun") by spaces, extracting
individual words as tokens.
o Output:

kotlin
Copy code
Token: C
Token: programming
Token: is
Token: fun

Summary of Output:

Copied String (using strcpy): Hello, C programming!


Concatenated String (using strcat): Hello, world!
Length of the string (using strlen): 23
String str3 is lexicographically less than str4 (using strcmp).
Substring found: C programming!
Token: C
Token: programming
Token: is
Token: fun

Case Study: Matrix Multiplication in C

Matrix multiplication is a fundamental operation in computer science, engineering, and


mathematics. Given two matrices, the goal is to multiply them together and produce a third
matrix. Let's walk through a case study to understand how matrix multiplication works, and
then see the C code to implement this.

Matrix Multiplication Basics

Suppose we have two matrices A and B, and we want to compute their product matrix C.

 Matrix A is of size m x n (m rows, n columns).


 Matrix B is of size n x p (n rows, p columns).
 The resulting matrix C will be of size m x p (m rows, p columns).
For matrix multiplication to be valid, the number of columns in matrix A must be equal to the
number of rows in matrix B (i.e., A's column size must match B's row size).

C Program to Perform Matrix Multiplication

Now, let's see a C program that implements matrix multiplication.

#include <stdio.h>

#define MAX 10

// Function to perform matrix multiplication


void multiplyMatrices(int first[MAX][MAX], int second[MAX][MAX], int
result[MAX][MAX], int row1, int col1, int row2, int col2) {
if (col1 != row2) {
printf("Matrix multiplication is not possible.\n");
return;
}

// Initializing the result matrix to 0


for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
result[i][j] = 0;
}
}

// Perform matrix multiplication


for (int i = 0; i < row1; i++) {
for (int j = 0; j < col2; j++) {
for (int k = 0; k < col1; k++) {
result[i][j] += first[i][k] * second[k][j];
}
}
}
}

// Function to display a matrix


void displayMatrix(int matrix[MAX][MAX], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}

int main() {
int first[MAX][MAX], second[MAX][MAX], result[MAX][MAX];
int row1, col1, row2, col2;

// Input for matrix A


printf("Enter rows and columns for first matrix: ");
scanf("%d %d", &row1, &col1);

printf("Enter elements of matrix A:\n");


for (int i = 0; i < row1; i++) {
for (int j = 0; j < col1; j++) {
scanf("%d", &first[i][j]);
}
}

// Input for matrix B


printf("Enter rows and columns for second matrix: ");
scanf("%d %d", &row2, &col2);

if (col1 != row2) {
printf("Matrix multiplication is not possible.\n");
return 1; // Exit if multiplication is not possible
}

printf("Enter elements of matrix B:\n");


for (int i = 0; i < row2; i++) {
for (int j = 0; j < col2; j++) {
scanf("%d", &second[i][j]);
}
}

// Multiply the matrices


multiplyMatrices(first, second, result, row1, col1, row2, col2);

// Display the result matrix


printf("Product of matrices:\n");
displayMatrix(result, row1, col2);

return 0;
}

Explanation of the Code:

1. Input matrices:
o First, the program takes the dimensions of matrix A (rows and columns) and matrix
B.
o Then, it takes the elements for both matrices.
2. Check for multiplication feasibility:
o Before multiplying, it checks if the number of columns in A is equal to the number of
rows in B. If not, matrix multiplication is not possible, and the program terminates.
3. Matrix Multiplication:
o The function multiplyMatrices() performs the multiplication using three nested
loops:
 The outer two loops iterate over the rows of matrix A and the columns of
matrix B.
 The innermost loop performs the summation for the product of the
corresponding elements.
4. Display Result:
o The resulting matrix is printed row by row.

Sample Input and Output:

Input:

Enter rows and columns for first matrix: 2 2


Enter elements of matrix A:
1 2
3 4
Enter rows and columns for second matrix: 2 2
Enter elements of matrix B:
5 6
7 8

Output:

Product of matrices:
19 22
43 50

You might also like