1. What is an Array?
In C, an array is a simple data structure that stores a collection of multiple items of the same data type under a single variable name.
Think of it like a row of mailboxes. The entire row has one name (e.g., "PO Box 100"), but each individual box can be accessed by its number (box #1, box #2, etc.).
Key Properties:
· Same Data Type: An array can hold 10 integers, or 50 floats, or 100 characters, but it cannot hold one integer and one float in the same array.
· Contiguous Memory: All elements of an array are stored next to each other in the computer's memory, in a continuous block. This makes it very fast to access them.
· Fixed Size: In C, the size of a basic array must be specified when you create it, and it cannot be changed later.
· Indexed: Each element in the array is identified by a unique number called an index.
2. One-Dimensional Arrays (1-D)
A one-dimensional (1-D) array is the simplest form, like a single list of items.
Declaring an Array
You declare an array by specifying its data type, name, and size (the number of elements it can hold).
Syntax:
data_type
array_name[size];
Example:
// Declares an array named 'marks' that can hold 10 integers.
int marks[10];
// Declares an array named 'prices' that can hold 5 floating-point numbers.
float prices[5];
Array Indexing
· Array elements are accessed using their index, which is an integer number.
· Crucial Rule: The first element in a C array is always at index 0.
· The last element is at index (size - 1).
So, for int marks[10];:
· The first element is marks[0].
· The second element is marks[1].
· ...
· The tenth (and last) element is marks[9].
Initializing an Array
You can give values to your array when you declare it.
// Method 1: Initialize all elements
int numbers[5] = {10, 20, 30, 40, 50};
// numbers[0] is 10, numbers[1] is 20, ..., numbers[4] is 50
// Method 2: Let the compiler count the size
int flexible[] = {1, 2, 3};
// The compiler automatically makes this an array of size 3
// Method 3: Partial initialization
int partial[5] = {10, 20};
// partial[0] is 10, partial[1] is 20
// All other elements (partial[2], partial[3], partial[4]) are automatically set to 0.
Accessing and Using Arrays (with Loops)
The most common way to work with arrays is by using a for loop to go through each element one by one.
Example Program 1: 1-D Array (Input,
Output, Sum)
This program creates an array of 5 integers, asks the user to enter values,
prints them back, and calculates their sum.
/* * Example 1: 1-D Array
* This program demonstrates how to declare, initialize (from user input),
* print, and process a one-dimensional array.
*/
#include <stdio.h>
int main() {
// 1. Declare an integer array of size 5
int scores[5];
int i; // 'i' is a common variable name for loop counters (index)
int sum = 0;
// 2. Get input from the user using a for loop
printf("Enter 5 scores:\n");
for (i = 0; i < 5; i++) {
printf("Score for student %d: ", i + 1);
// Store the input at the index 'i'
// &scores[i] means "the memory address of the element at index i"
scanf("%d", &scores[i]);
}
// 3. Print the array elements using another for loop
printf("\nThe scores you entered are:\n");
for (i = 0; i < 5; i++) {
printf("scores[%d] = %d\n", i, scores[i]);
}
// 4. Process the array (e.g., find the sum)
for (i = 0; i < 5; i++) {
sum = sum + scores[i]; // or sum += scores[i]
}
printf("\nTotal sum of scores: %d\n", sum);
// Calculate and print average
// We cast 'sum' to float to get a decimal result
float average = (float)sum / 5.0;
printf("Average score: %.2f\n", average);
return 0;
}
3. Two-Dimensional Arrays (2-D)
A 2-D array is like an "array of arrays." You can think of it as a table or a grid with rows and columns.
Declaring a 2-D Array
You specify the data type, name, number of rows, and number of columns.
Syntax:
data_type
array_name[rows][columns];
Example:
// Declares a 2D array (matrix) with 3 rows and 4 columns
int matrix[3][4];
Initializing a 2-D Array
You can initialize it using nested curly braces {}.
int table[2][3] = {
{1, 2, 3}, // Row 0: table[0][0]=1, table[0][1]=2, table[0][2]=3
{4, 5, 6} // Row 1: table[1][0]=4, table[1][1]=5, table[1][2]=6
};
// You can also write it on one line, but it's less readable
int table_oneline[2][3] = {{1, 2, 3}, {4, 5, 6}};
Accessing 2-D Arrays (with Nested Loops)
To process every element in a 2-D array, you need two loops: one "nested" inside the other.
· The outer loop iterates through the rows.
· The inner loop iterates through the columns for the current row.
Example Program 2: 2-D Array (Matrix
Printing)
This program initializes a 2x3 matrix and prints it to the console in a grid
format.
/*
* Example 2: 2-D Array
* This program demonstrates how to declare, initialize,
* and print a two-dimensional array (matrix).
*/
#include <stdio.h>
int main() {
// 1. Declare and initialize a 2D array with 2 rows and 3 columns
int matrix[2][3] = {
{10, 20, 30}, // Row 0
{40, 50, 60} // Row 1
};
int i, j; // i for row index, j for column index
printf("Printing the 2x3 matrix:\n");
// 2. Use nested loops to print the elements
// Outer loop for rows
for (i = 0; i < 2; i++) {
// Inner loop for columns
for (j = 0; j < 3; j++) {
// Print the element at [row i][column j]
printf("%d\t", matrix[i][j]); // \t adds a tab for spacing
}
// After printing all columns for a row, print a newline
printf("\n");
}
return 0;
}
4. Multi-Dimensional Arrays (3-D and beyond)
While 1-D and 2-D arrays are the most common, C supports arrays with more dimensions. A 3-D array can be visualized as a cube, or a collection of 2-D arrays.
You can think of it as [pages][rows][columns].
Declaring a 3-D Array
Syntax:
data_type
array_name[pages][rows][columns];
Example:
// Declares a 3D array with 2 "pages", 3 rows, and 4 columns
int data[2][3][4];
Initializing a 3-D Array
Initialization uses another level of nested braces.
int cube[2][2][3] = {
{ // Page 0
{1, 2, 3}, // Row 0 of Page 0
{4, 5, 6} // Row 1 of Page 0
},
{ // Page 1
{7, 8, 9}, // Row 0 of Page 1
{10, 11, 12} // Row 1 of Page 1
}
};
Accessing 3-D Arrays (with 3 Nested Loops)
To process every element, you now need three nested loops.
Example Program 3: 3-D Array
This program initializes and prints a 2x2x3 3-D array.
/*
* Example 3: 3-D Array
* This program demonstrates how to initialize and print
* a three-dimensional array.
*/
#include <stdio.h>
int main() {
// 1. Declare and initialize a 3D array [pages][rows][cols]
int cube[2][2][3] = {
{ {1, 2, 3}, {4, 5, 6} }, // Page 0
{ {7, 8, 9}, {10, 11, 12} } // Page 1
};
int i, j, k; // i for pages, j for rows, k for columns
printf("Printing the 2x2x3 3D array:\n");
// 2. Use three nested loops to print the elements
for (i = 0; i < 2; i++) { // Loop through pages
printf("Page %d:\n", i);
for (j = 0; j < 2; j++) { // Loop through rows
// Add indentation for rows
printf(" Row %d: ", j);
for (k = 0; k < 3; k++) { // Loop through columns
printf("%d ", cube[i][j][k]);
}
printf("\n"); // Newline after each row
}
printf("\n"); // Newline after each page
}
return 0;
}
5. Advantages and Disadvantages of Arrays
Advantages
1. Code Optimization: Less code is needed. You can retrieve or process many values just by using their index in a loop.
2. Random Access: You can instantly access any element if you know its index (e.g., myArray[5]). You don't have to go through elements 0-4 to get to 5.
3. Easy to Use: Good for storing and managing a collection of related data.
Disadvantages
1. Fixed Size (Static): The size of the array is fixed at compile time. You can't make it bigger or smaller while the program is running. (This is a major limitation, solved by "Dynamic Memory Allocation" which you'll learn in Unit 4).
2. Memory Wastage: If you declare an array int scores[100]; but only end up using 10 elements, you are still wasting the memory for the other 90 integers.
3. No "Out of Bounds" Checking: C does not stop you from trying to access myArray[20] even if the size is only myArray[10]. This will read or write to some random part of memory, causing bugs that are hard to find (this is called a "buffer overflow").