0% found this document useful (0 votes)
3 views

4.Introduction to Arrays, Strings

The document provides a comprehensive overview of array declaration, initialization, and operations in C programming, including one-dimensional, two-dimensional, and multi-dimensional arrays. It also covers matrix operations such as addition, multiplication, transpose, and symmetry, with detailed explanations and example code for each operation. Additionally, it highlights the importance of arrays and matrices in efficiently managing large datasets in various applications.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

4.Introduction to Arrays, Strings

The document provides a comprehensive overview of array declaration, initialization, and operations in C programming, including one-dimensional, two-dimensional, and multi-dimensional arrays. It also covers matrix operations such as addition, multiplication, transpose, and symmetry, with detailed explanations and example code for each operation. Additionally, it highlights the importance of arrays and matrices in efficiently managing large datasets in various applications.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

1.

Declaration and
Initialization of Arrays
In C programming, arrays are used to store multiple values of the same data type in a
contiguous block of memory. They allow for efficient storage and access of large amounts of
data.

1. Declaration and Initialization of Arrays


1-D (One-Dimensional) Arrays
Declaration:
c
Copy code
data_type array_name[size];

Example:
c
Copy code
int numbers[5]; // Declares an integer array of size 5


● Initialization:

Static Initialization: Values are assigned at the time of declaration.


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

Partial Initialization: Any unspecified elements are initialized to 0.


c
Copy code
int numbers[5] = {1, 2}; // Initializes numbers[2],
numbers[3], and numbers[4] to 0

2-D (Two-Dimensional) Arrays


Declaration:
c
Copy code
data_type array_name[rows][columns];

Example:
c
Copy code
int matrix[3][4]; // Declares a 2-D array with 3 rows and 4
columns

● Initialization:

Static Initialization:
c
Copy code
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};

Partial Initialization:
c
Copy code
int matrix[3][4] = {
{1, 2},
{3, 4},
{5, 6}
}; // The rest of the elements are initialized to 0

Multi-Dimensional Arrays (3-D and Higher)


Declaration:
c
Copy code
data_type array_name[size1][size2][size3]...[sizeN];

Example:
c
Copy code
int cube[2][3][4]; // Declares a 3-D array

Initialization:
c
Copy code
int cube[2][3][4] = {
{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
},
{
{13, 14, 15, 16},
{17, 18, 19, 20},
{21, 22, 23, 24}
}
};

2. Storing and Accessing Array Elements


1-D Arrays
Storing Elements: Elements can be assigned directly using the index.
c
Copy code
int numbers[5];
numbers[0] = 10; // Assigns 10 to the first element

Accessing Elements: Access elements using the index.


c
Copy code
int first_element = numbers[0];

Example:
c
Copy code
int numbers[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]); // Output: 1 2 3 4 5
}

2-D Arrays
Storing Elements: Use two indices [row][column] to assign values.
c
Copy code
int matrix[2][3];
matrix[0][0] = 10; // Assigns 10 to the first element in the
first row and column

Accessing Elements: Use two indices to access specific elements.


c
Copy code
int value = matrix[0][0];


Example:
c
Copy code
int matrix[2][3] = {{1, 2, 3}, {4, 5, 6}};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n"); // Output: 1 2 3
// 4 5 6
}

Multi-Dimensional Arrays (3-D Example)


Storing Elements: Use three indices to assign values.
c
Copy code
int cube[2][3][4];
cube[0][0][0] = 10; // Assigns 10 to the element at the start
of the 3-D array

Accessing Elements: Use three indices to access specific elements.


c
Copy code
int value = cube[0][0][0];

Example:
c
Copy code
int cube[2][2][2] = {
{
{1, 2},
{3, 4}
},
{
{5, 6},
{7, 8}
}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
for (int k = 0; k < 2; k++) {
printf("%d ", cube[i][j][k]); // Output: 1 2 3 4 5
6 7 8
}
printf("\n");
}
printf("\n");
}

Summary of Array Operations


1. Declaration: Specifies the type and size of the array.
2. Initialization: Sets initial values, either fully or partially.
3. Storing: Assign values using indices.
4. Accessing: Retrieve values using indices.

Arrays are essential for managing large sets of data efficiently in C, especially when handling
data in structured formats (like matrices in mathematics or multi-layered structures in
scientific computing).
matrix operation
Certainly! Let's go through each matrix operation—addition, multiplication, transpose, and
symmetry—in detail, with explanations of the concepts, formulas, and step-by-step code
examples for each.

1. Matrix Addition
Matrix addition is the operation of adding two matrices by summing the corresponding
elements. To perform matrix addition:

● Both matrices must have the same dimensions.


● The resulting matrix will also have the same dimensions.

Formula

Given two matrices AAA and BBB of the same dimensions m×nm \times nm×n (where mmm
is the number of rows and nnn is the number of columns), the resulting matrix CCC will have
each element calculated as:

C[i][j]=A[i][j]+B[i][j]C[i][j] = A[i][j] + B[i][j]C[i][j]=A[i][j]+B[i][j]

#include<stdio.h>

int main()

int i,j, A[2][2]= {{2,4},{3,6}};

int B[2][2]={{6,8}, {9,11}};

int C[2][2];

for (i=0; i<2 ; i++)

for (j=0; j<2; j++)

printf("%d ", C[i][j] = A[i][j] + B[i][j]);

printf("\n");

return(0);

}
Example Code

Here’s a C program that adds two 2x2 matrices:

c
Copy code
#include <stdio.h>

void addMatrices(int rows, int cols, int A[rows][cols], int


B[rows][cols], int C[rows][cols]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}
}

int main() {
int A[2][2] = {{1, 2}, {3, 4}};
int B[2][2] = {{5, 6}, {7, 8}};
int C[2][2];

addMatrices(2, 2, A, B, C);

printf("Result of matrix addition:\n");


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", C[i][j]); // Output: 6 8 10 12
}
printf("\n");
}
return 0;
}

Explanation

1. We define addMatrices() to take the dimensions of the matrices and add


corresponding elements.
2. For each element at position (i, j), the sum of A[i][j] and B[i][j] is stored
in C[i][j].

The output is:

Copy code
6 8
10 12
2. Matrix Multiplication
Matrix multiplication is the operation of multiplying two matrices. Unlike addition, matrix
multiplication has different rules:

● The number of columns in the first matrix must equal the number of rows in the
second matrix.
● If matrix AAA is of dimensions m×nm \times nm×n and matrix BBB is of
dimensions n×pn \times pn×p, the resulting matrix CCC will have dimensions
m×pm \times pm×p.

Formula

For two matrices AAA and BBB:

C[i][j]=∑k=0n−1A[i][k]×B[k][j]C[i][j] = \sum_{k=0}^{n-1} A[i][k] \times


B[k][j]C[i][j]=k=0∑n−1A[i][k]×B[k][j]

Example Code

Here’s a C program that multiplies a 2x3 matrix with a 3x2 matrix:

c
Copy code
#include <stdio.h>

void multiplyMatrices(int m, int n, int p, int A[m][n], int


B[n][p], int C[m][p]) {
for (int i = 0; i < m; i++) {
for (int j = 0; j < p; j++) {
C[i][j] = 0;
for (int k = 0; k < n; k++) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
}

int main() {
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[3][2] = {{7, 8}, {9, 10}, {11, 12}};
int C[2][2];

multiplyMatrices(2, 3, 2, A, B, C);

printf("Result of matrix multiplication:\n");


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", C[i][j]); // Output: 58 64 139 154
}
printf("\n");
}
return 0;
}

Explanation

1. multiplyMatrices() takes matrices A and B and calculates each element of C


by taking the dot product of the appropriate row of A and column of B.
2. The innermost loop handles the summation by iterating through each element in the
row-column pairs.

The output is:

Copy code
58 64
139 154

3. Transpose of a Matrix
The transpose of a matrix is obtained by flipping it over its diagonal, i.e., converting rows into
columns and columns into rows.

Formula

For a matrix AAA of dimensions m×nm \times nm×n, the transpose matrix ATA^TAT has
dimensions n×mn \times mn×m, with:

AT[i][j]=A[j][i]A^T[i][j] = A[j][i]AT[i][j]=A[j][i]

Example Code

Here’s a C program that computes the transpose of a 2x3 matrix:

c
Copy code
#include <stdio.h>

void transposeMatrix(int rows, int cols, int A[rows][cols],


int T[cols][rows]) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
T[j][i] = A[i][j];
}
}
}

int main() {
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int T[3][2];
transposeMatrix(2, 3, A, T);

printf("Transpose of the matrix:\n");


for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
printf("%d ", T[i][j]); // Output: 1 4 2 5 3 6
}
printf("\n");
}
return 0;
}

Explanation

1. transposeMatrix() takes each element in row i and column j of A and places


it in row j and column i of T.
2. This effectively swaps rows with columns.

The output is:

Copy code
1 4
2 5
3 6

4. Symmetry of a Matrix
A matrix is symmetric if it is square (i.e., number of rows equals number of columns) and
each element A[i][j]A[i][j]A[i][j] is equal to A[j][i]A[j][i]A[j][i].

Condition

For a square matrix AAA to be symmetric:

A[i][j]=A[j][i]for all i and jA[i][j] = A[j][i] \quad \text{for all } i \text{ and } jA[i][j]=A[j]
[i]for all i and j

Example Code

Here’s a C program that checks if a 3x3 matrix is symmetric:

c
Copy code
#include <stdio.h>
#include <stdbool.h>

bool isSymmetric(int size, int A[size][size]) {


for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (A[i][j] != A[j][i]) {
return false;
}
}
}
return true;
}

int main() {
int A[3][3] = {
{1, 2, 3},
{2, 5, 6},
{3, 6, 9}
};

if (isSymmetric(3, A)) {
printf("The matrix is symmetric.\n");
} else {
printf("The matrix is not symmetric.\n");
}

return 0;
}

#include <stdbool.h> is a preprocessor directive in C that includes the stdbool.h


header file, which enables you to use Boolean data types (bool), values (true and false),
and logical operations. This header is part of the C99 standard, so if you're using a C99-
compliant compiler, it will be supported.

Here’s a quick overview:

● bool: Defines a Boolean type, so instead of using int (like int flag = 0; or
int flag = 1;), you can directly use bool flag = true; or bool flag
= false;.
● true and false: Predefined macros representing Boolean true (1) and false (0).
● Logical operations: Makes code easier to read and work with standard logical
operations.

Here's a small example:

c
Copy code
#include <stdio.h>
#include <stdbool.h>
int main() {
bool isFinished = false;

if (!isFinished) {
printf("Process is not finished.\n");
isFinished = true;
}

if (isFinished) {
printf("Process is now finished.\n");
}

return 0;
}

This code makes use of bool, true, and false to control the flow more clearly.

Explanation

1. isSymmetric() checks each pair of elements A[i][j]A[i][j]A[i][j] and A[j][i]A[j]


[i]A[j][i] in a square matrix.
2. If all pairs are equal, it returns true; otherwise, it returns false.

For the given matrix, the output is:

csharp
Copy code
The matrix is symmetric.

Summary
1. Addition: Sum corresponding elements of two matrices with the same dimensions.
2. Multiplication: Take the dot product of rows and columns for compatible matrices.
3. Transpose: Convert rows to columns.
4. Symmetry Check: Ensure that each element is equal to its transposed position for a
square matrix.

Each of these operations is widely used in scientific computing, graphics, data analysis, and
machine learning.
Strings
Certainly! Let's go over each part of string handling in C in detail, covering declaration,
initialization, reading and writing, string operations, and manipulation functions.

1. Declaration and Initialization of Strings

In C, strings are arrays of char data type, with the end of the string marked by a special
character '\0' (null character). The null character indicates where the string ends, allowing
functions to find the end of the string.

Declaration:

To declare a string, you define it as an array of characters. For example:

c
Copy code
char str1[10];

This statement reserves space for a string of up to 9 characters plus the null character ('\0').

Initialization:

Strings can be initialized in multiple ways:

Direct Initialization:
c
Copy code
char str[] = "Hello";

1. This creates a character array of size 6 (H, e, l, l, o, and \0), with the compiler
automatically determining the array size based on the length of the string.

Manual Initialization with Fixed Size:


c
Copy code
char str[10] = "World";

2. Here, the array has space for 10 characters. "World" is stored with a null
terminator, and the remaining elements are filled with '\0'.

Individual Character Initialization:


c
Copy code
char str[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

3. This method explicitly initializes each character, ensuring the string is null-
terminated.

2. Reading and Writing Strings


To work with strings from user input or for displaying strings, we use functions like
scanf(), fgets(), and printf().
Reading Strings:

1. Using scanf():
○ scanf() reads a word (up to the first whitespace).

Example:
c
Copy code
char str[50];
printf("Enter a word: ");
scanf("%49s", str); // Reads a word with a maximum of 49
characters


○ Limitations: scanf() doesn’t read spaces or special characters as part of
the string.
2. Using fgets():
○ fgets() reads an entire line including spaces, until a newline ('\n') or
the specified character limit is reached.

Example:
c
Copy code
char str[50];
printf("Enter a line of text: ");
fgets(str, sizeof(str), stdin); // Reads up to 49 characters
and adds '\0'

Writing Characters into Strings:

Characters can be written into strings either individually or using functions.

Writing Individual Characters:


c
Copy code
char str[10];
str[0] = 'H';
str[1] = 'i';
str[2] = '\0'; // Adding null terminator to end the string

1.
2. Using strcpy():
○ strcpy(destination, source) copies one string to another.

Example:
c
Copy code
char str1[10];
strcpy(str1, "Hello");

3. String Operations
String operations like concatenation, comparison, and length calculation are performed using
standard library functions.

Concatenation:

● strcat(destination, source): Appends the source string to the


destination string.

Example:
c
Copy code
char str1[50] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2); // str1 now contains "Hello, World!"

Comparison:

● strcmp(str1, str2): Compares two strings.


○ Returns 0 if they are identical, a positive number if str1 > str2, and a
negative number if str1 < str2.

Example:
c
Copy code
if (strcmp(str1, str2) == 0) {
printf("Strings are equal.\n");
} else {
printf("Strings are not equal.\n");
}

#include <stdio.h>

#include<string.h>

int main()

char str1[20]="hello";

char str2[20]="Hello";

if(strcmp(str1,str2)==0)
{printf(" Strings are equal");

else

printf(" strings are not equal: ");

return 0;

Length Calculation:

● strlen(str): Returns the length of the string excluding the null terminator.

Example:
c
Copy code
size_t len = strlen(str1);
printf("Length: %zu\n", len);

Explanation

● strlen(str1): Calculates the length of the string str1


(excluding the null terminator).
● %zu: Format specifier for size_t (which is used for sizes
and array indexes in C).

4. Character and String Manipulation Functions


C provides a wide range of functions for character and string manipulation. Here’s an
overview of some of the most useful ones.

Common String Manipulation Functions (<string.h>):

1. strlen(const char *str): Returns the length of the string.


2. strcpy(char *dest, const char *src): Copies src to dest.
3. strcat(char *dest, const char *src): Appends src to the end of
dest.
4. strcmp(const char *str1, const char *str2): Compares two strings
lexicographically.
5. strchr(const char *str, int ch): Returns a pointer to the first
occurrence of ch in str.
6. strstr(const char *haystack, const char *needle): Returns a
pointer to the first occurrence of needle in haystack.

Character Manipulation Functions (<ctype.h>):

1. toupper(int ch): Converts ch to uppercase.


2. tolower(int ch): Converts ch to lowercase.
3. isalpha(int ch): Checks if ch is an alphabetic character.
4. isdigit(int ch): Checks if ch is a digit.

5. Example Program
Here’s an example that demonstrates string input/output and several string operations.

c
Copy code
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main() {
char str1[100], str2[50], concatenated[150];

// Reading strings
printf("Enter first string: ");
fgets(str1, sizeof(str1), stdin);

printf("Enter second string: ");


fgets(str2, sizeof(str2), stdin);

// Remove newline character if present


str1[strcspn(str1, "\n")] = '\0';
str2[strcspn(str2, "\n")] = '\0';

// String length
printf("Length of first string: %zu\n", strlen(str1));

// Concatenation
strcpy(concatenated, str1); // Copy str1 into concatenated
strcat(concatenated, str2); // Append str2 to concatenated
printf("Concatenated string: %s\n", concatenated);

// Comparison
if (strcmp(str1, str2) == 0) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
// Character manipulation - convert to uppercase
for (int i = 0; str1[i]; i++) {
str1[i] = toupper(str1[i]); // Convert to uppercase
}

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

return 0;
}

Explanation of the Example:

1. Reading Strings: fgets() is used to read two strings.


2. Removing Newline: strcspn() is used to remove any newline character added by
fgets().
3. String Operations:
○ We calculate the length using strlen().
○ strcat() is used to concatenate str1 and str2.
○ strcmp() checks if the two strings are identical.
○ toupper() is used to convert each character in str1 to uppercase.

Summary

In C, strings are arrays of characters that end with '\0'. Using functions in <string.h>
and <ctype.h>, we can manipulate strings and perform operations like concatenation,
comparison, and case conversion. This gives you a powerful toolkit for working with text and
characters in C!

You might also like