Skip to main content

← Back to C Course Foundations

Two-Dimensional Numeric Array (C)

Learning Objectives

  • Declare and initialize 2D numeric arrays.
  • Perform addition, subtraction, multiplication, and transpose.
  • Compute element addresses in row-major and column-major order.

Concept

A 2D array stores values in rows and columns. In C, memory is stored in row-major order by default.

Algorithm (Matrix Addition)

  1. Read matrix dimensions r and c.
  2. Input matrix A[r][c] and B[r][c].
  3. For each cell (i, j), compute C[i][j] = A[i][j] + B[i][j].
  4. Print matrix C.

C Example

#include <stdio.h>

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

for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
C[i][j] = A[i][j] + B[i][j];
}
}

printf("Result (A + B):\n");
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
printf("%d ", C[i][j]);
}
printf("\n");
}

int i = 1, j = 2;
int cols = 3;
int base = 1000; // assumed base address
int size = sizeof(int);
int row_major_addr = base + ((i * cols + j) * size);
printf("Address of A[1][2] (row-major formula): %d\n", row_major_addr);

return 0;
}

Dry Run (Addition)

  • A[0][1] = 2, B[0][1] = 5 -> C[0][1] = 7
  • A[1][2] = 6, B[1][2] = 1 -> C[1][2] = 7

Output matrix:

7 7 7
7 7 7

Common Mistakes

  • Mismatched matrix dimensions for operations.
  • Wrong loop bounds (i < r, j < c).
  • Confusing row-major and column-major formulas.

Practice

  1. Write matrix subtraction.
  2. Write matrix transpose.
  3. Implement 2x2 matrix multiplication.

📍 Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
📍 Address
2/66 Faram Street, Rustompura
Surat395002, Gujarat, India
📞 Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition — Areas We Serve in Surat

AdajanAlthanAmroliAthwaAthwalinesBhagalBhatarBhestanCanal RoadChowkCitylightDumasGaurav PathGhod Dod RoadHaziraJahangirpuraKamrejKapodraKatargamLimbayatMagdallaMajura GateMota VarachhaNanpuraNew CitylightOlpadPalPandesaraParle PointPiplodPunaRanderRing RoadRustampuraSachinSalabatpuraSarthanaSosyo CircleUdhnaVarachhaVed RoadVesuVIP Road
📞 Call Sir💬 WhatsApp Sir