Skip to content

Arrays in C

Collection of elements of the same data type.

  • An array of structures is a collection of structures, all of the same type, stored in contiguous memory locations.
  • It is useful for storing data sets with multiple attributes, like a list of students, employees, or products.

Features:

  • Same Data Type: All elements must have the same type.
  • Fixed Size: Declared at compile-time, cannot be resized dynamically.
  • Indexing: Elements are accessed using zero-based indexing (0 to n-1).
  • Contiguous Memory Allocation: Faster access.

Types of Arrays:

  • One-Dimensional (1D) Array
  • Two-Dimensional (2D) Array
  • Multi-Dimensional Arrays

One-Dimensional Array: A single row of elements.

#include <stdio.h>
int main() {
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
return 0;
}

Two-Dimensional Array (Matrix) Stores data in rows and columns (table-like structure).

#include <stdio.h>
int main() {
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");
}
return 0;
}

Multi-Dimensional Array Extension of 2D arrays into 3D or more.

#include <stdio.h>
int main() {
int cube[2][2][2] = {
};
}

Limitations of Arrays:

  • Fixed size (cannot grow/shrink dynamically).
  • All elements must be of the same type.
  • Memory waste if declared too large.
  • Organizes data: Keeps related data together in a structured form.
  • Easy access: Access each element using the array index and each member using the dot operator.
  • Scalability: Easy to add more structures to the array without changing the code structure significantly.
#include <stdio.h>
int main()
{
// Initialize a 2x4 array named 'marks' with some sample values
int marks[2][4] = {{45, 234, 2, 3},
{3, 2, 3, 3}};
// for(int i = 0; i < 4; i++)
// {
// printf("Enter the value of %d element of the array\n", i);
// scanf("%d", &marks[i]);
// }
// Loop to display the values of the 'marks' array
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 4; j++)
{
// printf("The value of %d, %d element of the array is %d\n", i, j, marks[i][j]);
// This code now prints the values of the 'marks' array in a tabular format.
printf("%d ", marks[i][j]);
}
printf("\n"); // Move to the next line after printing a row
}
// marks[0] = 34;
// printf("Marks of student 1 is %d\n", marks[0]);
// marks[0] = 4;
// marks[1] = 24;
// marks[2] = 34;
// marks[3] = 44;
// printf("Marks of student 1 is %d\n", marks[0]);
return 0;
}