Relationship between Pointers and Arrays
In C, arrays and pointers are closely related. The name of an array is essentially a pointer to the first element of the array. For example, if you have an array int arr[10];
, the name arr
can be used as a pointer to the first element, i.e., arr
is equivalent to &arr[0]
.
Here are some key points:
- Array Name as Pointer: The name of an array acts like a pointer to its first element.
- Pointer Arithmetic: You can perform arithmetic operations on pointers to traverse the array.
- Access Elements: Elements of an array can be accessed using both array notation (
arr[i]
) and pointer notation (*(arr + i)
).
Example in C:
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr; // Pointer to the first element of the array
for (int i = 0; i < 5; i++) {
// Accessing elements using both array and pointer notation
printf("arr[%d] = %d, *(ptr + %d) = %d\n", i, arr[i], i, *(ptr + i));
}
return 0;
}
Program to Print Transpose of a 2D Matrix
Here is a C program to read a 2D matrix from the user and print its transpose:
#include <stdio.h>
#define MAX_ROWS 10
#define MAX_COLS 10
int main() {
int matrix[MAX_ROWS][MAX_COLS];
int transpose[MAX_COLS][MAX_ROWS];
int rows, cols;
// Getting matrix dimensions from the user
printf("Enter the number of rows and columns of the matrix: ");
scanf("%d %d", &rows, &cols);
// Reading the matrix elements from the user
printf("Enter the elements of the matrix:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("Element [%d][%d]: ", i, j);
scanf("%d", &matrix[i][j]);
}
}
// Calculating the transpose of the matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
transpose[j][i] = matrix[i][j];
}
}
// Printing the transpose of the matrix
printf("\nTranspose of the matrix:\n");
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
printf("%d ", transpose[i][j]);
}
printf("\n");
}
return 0;
}
Explanation
- Matrix Input: The program first takes the number of rows and columns of the matrix from the user and then reads the matrix elements.
- Transpose Calculation: The transpose of the matrix is calculated by swapping rows with columns.
- Matrix Output: Finally, the transposed matrix is printed.
Comments:
- The
matrix
array stores the original matrix. - The
transpose
array stores the transposed matrix. - Nested loops are used to read the matrix elements and calculate the transpose.
- The outer loop runs through each row, and the inner loop runs through each column.