🚀 Arrays in C Programming – Complete Guide (1D & 2D) with Fully Commented Programs + Practice Set + Viva Q&A
📚 Part 9 – C Programming Complete Guide (Step-by-Step)
📌 Continue Learning
📖 Read Previous Parts:
-
Part 1 – Introduction to C
-
Part 2 – Variables & Data Types
-
Part 3 – Input & Output
-
Part 4 – Operators
-
Part 5 – Decision Making
-
Part 6 – Loops
-
Part 7 – Functions
Part 8 – Pointers
📌 Introduction to Arrays
In C programming, when we need to store multiple values of the same data type, declaring separate variables becomes inefficient and messy.
❌ Not Recommended
int a = 10; // Store first value
int b = 20; // Store second value
int c = 30; // Store third value
✅ Better Approach (Using Array)
int arr[3] = {10,20,30}; // Store multiple values in one array
An array stores elements in contiguous memory locations under a single name.
🔹 One-Dimensional Array (1D Array)
A 1D array stores elements in a linear structure (single row).
Syntax
data_type array_name[size]; // Declare array
Example:
int arr[5]; // Integer array of size 5
✔ Index starts from 0
✔ Last index = size - 1
✔ Stored in contiguous memory
📦 Memory Representation (1D Array)
If:
int arr[3] = {10,20,30};
Memory stores like:
| Index | Value |
|---|---|
| 0 | 10 |
| 1 | 20 |
| 2 | 30 |
Address formula:
Address of arr[i] = Base Address + (i × size_of_data_type)
🧠 Access Time Complexity: O(1)
🔹 Two-Dimensional Array (2D Array)
A 2D array stores elements in rows and columns (matrix format).
Syntax
data_type array_name[rows][columns];
Example:
int arr[2][3]; // 2 rows, 3 columns
Total elements = rows × columns
📦 Memory Representation (Row-Major Order)
Example matrix:
1 2
3 4
Stored in memory as:
1 → 2 → 3 → 4
Rows stored one after another.
🧠 Traversal Time Complexity: O(n × m)
📌 Memory Representation of 1D and 2D Arrays in C
Understanding syntax is not enough — we must also understand how arrays are stored in memory.
In C programming:
-
Arrays are stored in contiguous memory locations
-
Each element occupies memory based on the size of its data type
-
2D arrays are stored using Row-Major Order
Let us visualize how memory allocation actually works.
🔎 Explanation of the Diagram
In the 1D array:
-
The first element is stored at the base address
-
Each next element is stored at:
Base Address + (Index × Size of Data Type)
If int takes 4 bytes, memory increases like:
1000 → 1004 → 1008 → 1012
This shows sequential contiguous memory allocation.
In the 2D array:
-
C uses Row-Major Order
-
Entire first row is stored first
-
Then second row is stored
-
Memory continues sequentially row by row
This is why even a 2D array is internally stored as a continuous 1D block of memory.
🎯 Why This Is Important in Interviews
Interviewers often ask:
-
How is a 2D array stored internally?
-
What is row-major order?
-
How is address calculated?
Understanding memory layout proves that you truly understand arrays beyond syntax.
📌 Real-Life Applications of Arrays
✔ Searching algorithms
✔ Sorting algorithms
✔ Matrix operations
✔ Game boards
✔ Image processing
✔ Data structures
✔ Dynamic programming
🏆 PRACTICE SECTION (6 Fully Commented Programs)
🔥 Practice 1: Count Even and Odd Numbers
#include <stdio.h> // Include standard input-output library
int main() // Main function begins
{
int arr[5] = {1,2,3,4,5}; // Declare and initialize array with 5 elements
int i; // Loop control variable
int even = 0, odd = 0; // Initialize counters for even and odd numbers
for(i = 0; i < 5; i++) // Loop from index 0 to 4
{
if(arr[i] % 2 == 0) // Check if element is divisible by 2
{
even++; // Increment even counter
}
else // If not divisible by 2
{
odd++; // Increment odd counter
}
}
printf("Even = %d\n", even); // Display total even numbers
printf("Odd = %d", odd); // Display total odd numbers
return 0; // End program
}
✅ Output:
Even = 2
Odd = 3
🧠 Time Complexity: O(n)
🔥 Practice 2: Linear Search
#include <stdio.h> // Include standard input-output library
int main() // Main function starts
{
int arr[5] = {10,20,30,40,50}; // Initialize array with 5 values
int key = 30; // Value to search in array
int i; // Loop variable
int found = 0; // Flag variable (0 means not found)
for(i = 0; i < 5; i++) // Traverse array
{
if(arr[i] == key) // Compare current element with key
{
found = 1; // Set flag to indicate found
break; // Exit loop
}
}
if(found == 1) // If found flag is 1
printf("Element Found"); // Print found message
else // Otherwise
printf("Element Not Found");// Print not found message
return 0; // End program
}
✅ Output:
Element Found
🧠 Time Complexity: O(n)
🔥 Practice 3: Reverse Array
#include <stdio.h> // Include library
int main() // Main function
{
int arr[5] = {1,2,3,4,5}; // Initialize array
int i; // Loop variable
printf("Reversed Array:\n"); // Print heading
for(i = 4; i >= 0; i--) // Start loop from last index to first
{
printf("%d ", arr[i]); // Print element in reverse order
}
return 0; // End program
}
✅ Output:
Reversed Array:
5 4 3 2 1
🧠 Time Complexity: O(n)
🔥 Practice 4: Matrix Addition (2D Array)
#include <stdio.h> // Include standard library
int main() // Main function starts
{
int a[2][2] = {{1,2},{3,4}}; // First 2x2 matrix
int b[2][2] = {{5,6},{7,8}}; // Second 2x2 matrix
int sum[2][2]; // Matrix to store result
int i, j; // Loop variables
for(i = 0; i < 2; i++) // Loop through rows
{
for(j = 0; j < 2; j++) // Loop through columns
{
sum[i][j] = a[i][j] + b[i][j]; // Add corresponding elements
}
}
printf("Result Matrix:\n"); // Print heading
for(i = 0; i < 2; i++) // Print result matrix
{
for(j = 0; j < 2; j++)
{
printf("%d ", sum[i][j]); // Display each element
}
printf("\n"); // Move to next line
}
return 0; // End program
}
✅ Output:
Result Matrix:
6 8
10 12
🧠 Time Complexity: O(n²)
🔥 Practice 5: Transpose of Matrix
#include <stdio.h> // Include standard library
int main() // Main function
{
int arr[2][2] = {{1,2},{3,4}}; // Initialize 2x2 matrix
int i, j; // Loop variables
printf("Transpose Matrix:\n"); // Print heading
for(i = 0; i < 2; i++) // Loop rows
{
for(j = 0; j < 2; j++) // Loop columns
{
printf("%d ", arr[j][i]); // Swap row and column indices
}
printf("\n"); // New line after each row
}
return 0; // End program
}
✅ Output:
Transpose Matrix:
1 3
2 4
🧠 Time Complexity: O(n²)
🔥 Practice 6: Second Largest Element
#include <stdio.h> // Include standard library
int main() // Main function
{
int arr[5] = {10,45,2,99,23}; // Initialize array
int i; // Loop variable
int largest, second; // Variables to store largest and second largest
largest = second = arr[0]; // Assume first element as largest initially
for(i = 1; i < 5; i++) // Traverse from second element
{
if(arr[i] > largest) // If current element is greater than largest
{
second = largest; // Update second largest
largest = arr[i]; // Update largest
}
else if(arr[i] > second && arr[i] != largest) // Check for second largest
{
second = arr[i]; // Update second largest
}
}
printf("Second Largest = %d", second); // Print second largest value
return 0; // End program
}
✅ Output:
Second Largest = 45
🧠 Time Complexity: O(n)
🎯 Viva Questions with Detailed Answers
1️⃣ What is an Array in C?
An array in C is a collection of elements of the same data type stored in contiguous memory locations under a single name.
Instead of declaring multiple variables separately, an array allows us to store multiple values efficiently and access them using an index.
For example:
int arr[5];
Here:
-
arris the array name -
5is the size -
Index starts from
0 -
Last index =
size - 1
Arrays improve:
-
Code readability
-
Memory management
-
Data handling efficiency
2️⃣ What is the difference between 1D and 2D array?
A 1D array stores elements in a linear format (single row), while a 2D array stores elements in rows and columns (matrix format).
| 1D Array | 2D Array |
|---|---|
| Uses only one index | Uses two indexes (row and column) |
| Accessed using: arr[i] | Accessed using: arr[row][column] |
| Represents a single list of values | Represents a matrix or table format |
| Declared as: int arr[5]; | Declared as: int arr[2][3]; |
| Total elements = size | Total elements = rows × columns |
3️⃣ What is Row-Major Order in 2D Array?
Row-major order means that elements of a 2D array are stored in memory row by row.
Example Matrix:
1 2
3 4
Memory stores elements as:
1 → 2 → 3 → 4
First entire row is stored, then next row.
This is important because it affects:
-
Memory understanding
-
Pointer arithmetic
-
Performance
4️⃣ What is an Out-of-Bound Error in Array?
An out-of-bound error occurs when we try to access an index that is outside the valid range of the array.
Example:
int arr[5];
Valid indexes:
0, 1, 2, 3, 4
Invalid:
arr[5] ❌
arr[-1] ❌
Accessing invalid indexes leads to:
-
Undefined behavior
-
Garbage values
-
Program crash
C does not automatically check array bounds.
5️⃣ What is the difference between Array and Pointer?
| Array | Pointer |
|---|---|
| Fixed size (defined at compile time) | Can change the address it points to |
| Memory allocated at compile time | Memory can be allocated dynamically using malloc() |
| Array name represents base address (constant) | Pointer stores a memory address |
| Cannot be reassigned to another address | Can be reassigned to point to another variable |
| Size of array is fixed once declared | Pointer size is fixed, but it can point to different data types |
int arr[5]; // Array
int *ptr; // Pointer
An array name acts like a constant pointer to its first element.
6️⃣ Can we change the size of an array at runtime?
No.
In normal static arrays, the size must be fixed at compile time.
Example:
int arr[5];
You cannot change size later.
However, dynamic memory allocation using malloc() or calloc() allows flexible size at runtime.
Example:
int *arr = (int*)malloc(5 * sizeof(int));
This is dynamic array creation.
7️⃣ Why does array index start from 0?
Array indexing starts from 0 because:
The index represents the offset from the base address.
Formula:
Address of arr[i] = Base Address + (i × size_of_data_type)
When i = 0:
Address = Base Address
So first element starts at index 0.
🎯 Interview Edge Cases (Detailed Explanation)
Thinking about edge cases shows deep understanding of logic, memory behavior, and real-world programming scenarios.
✔ 1️⃣ What if array size is 0?
💡 Explanation:
If the array size is 0, it means:
-
No memory is allocated for elements.
-
There are no values to process.
-
Any attempt to access
arr[0]will cause undefined behavior.
⚠ Why This Is Important:
In C, if you try to:
int arr[0]; // Not valid in standard C
Or dynamically:
int *arr = malloc(0);
Accessing arr[0] may:
-
Crash the program
-
Return garbage value
-
Cause segmentation fault
✅ Safe Handling:
Before processing an array:
if (size <= 0)
{
printf("Array is empty.\n");
return;
}
🎯 Interview Insight:
A good programmer always validates input size before looping.
✔ 2️⃣ What if all elements are equal?
Example:
5 5 5 5 5
💡 Explanation:
If all elements are equal:
-
Maximum = Minimum
-
Searching works normally
-
Sorting will not change array
-
Duplicate checks will detect duplicates
⚠ Logical Trap:
If your logic assumes:
if (arr[i] > max)
It still works.
But if finding second largest:
You must handle:
-
No distinct second largest element exists.
✅ Correct Approach:
While finding second largest:
-
Ensure distinct comparison
-
Use condition:
if (arr[i] != max)
🎯 Interview Insight:
This tests whether you understand distinct vs duplicate values.
✔ 3️⃣ What if matrix is non-square?
Example:
2 x 3 matrix
💡 Explanation:
A non-square matrix has:
Rows ≠ Columns
Some operations are NOT possible:
❌ Diagonal sum (only valid for square matrix)
❌ Transpose in same memory (size changes)
⚠ Common Mistake:
Students assume:
for(i = 0; i < n; i++)
for(j = 0; j < n; j++)
This only works for square matrices.
✅ Safe Handling:
Always use:
for(i = 0; i < rows; i++)
for(j = 0; j < cols; j++)
Before diagonal logic:
if(rows != cols)
{
printf("Diagonal not possible.\n");
}
🎯 Interview Insight:
This checks if you understand matrix dimensions properly.
✔ 4️⃣ What if duplicate largest elements exist?
Example:
10 20 30 30 5
💡 Explanation:
Here:
Largest = 30
But appears twice.
⚠ Problem Case:
If finding:
-
Second largest distinct number
Then answer is:
20 (not 30 again)
❌ Wrong Logic:
if(arr[i] > second)
This may again pick 30.
✅ Correct Logic:
if(arr[i] > second && arr[i] < max)
This ensures:
-
Second largest is strictly less than max.
🎯 Interview Insight:
Interviewer checks:
-
Can you handle duplicates?
-
Do you understand strict comparison?
🧠 Why Edge Cases Matter?
In real-world software:
-
Inputs are unpredictable
-
Users make mistakes
-
Data may be empty
-
Values may repeat
-
Dimensions may mismatch
A programmer who thinks about edge cases:
-
Writes safe code
-
Avoids crashes
-
Handles errors properly
-
Thinks like an engineer, not just a coder
🚨 Common Mistakes
❌ Accessing invalid index
❌ Wrong loop condition
❌ Forgetting initialization
❌ Mixing row & column
❌ Not checking bounds
🏁 Final Conclusion
Arrays are the foundation of:
✔ Searching
✔ Sorting
✔ Matrix operations
✔ Strings
✔ Data structures
Mastering arrays makes advanced programming much easier.
“Writing code is easy. Writing safe, edge-case-proof code is what makes you a professional.”
📌 Keep Learning. Keep Coding. Keep Growing.
✨ Written by Krishna Popat
🌱 Founder, Learning Growth Hub
Comments
Post a Comment