4.Introduction to Arrays, Strings
4.Introduction to Arrays, Strings
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.
Example:
c
Copy code
int numbers[5]; // Declares an integer array of size 5
●
● Initialization:
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
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}
}
};
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
●
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
}
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");
}
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:
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:
#include<stdio.h>
int main()
int C[2][2];
printf("\n");
return(0);
}
Example Code
c
Copy code
#include <stdio.h>
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);
Explanation
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
Example Code
c
Copy code
#include <stdio.h>
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);
Explanation
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
c
Copy code
#include <stdio.h>
int main() {
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int T[3][2];
transposeMatrix(2, 3, A, T);
Explanation
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
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
c
Copy code
#include <stdio.h>
#include <stdbool.h>
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;
}
● 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.
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
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.
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:
c
Copy code
char str1[10];
This statement reserves space for a string of up to 9 characters plus the null character ('\0').
Initialization:
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.
2. Here, the array has space for 10 characters. "World" is stored with a null
terminator, and the remaining elements are filled with '\0'.
3. This method explicitly initializes each character, ensuring the string is null-
terminated.
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'
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:
Example:
c
Copy code
char str1[50] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2); // str1 now contains "Hello, World!"
Comparison:
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
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
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);
// 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
}
return 0;
}
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!