Skip to main content

1D Arrays in C: Storing Lists of Data πŸ—οΈ

1D Arrays in C: Storing Lists of Data is a core C concept covering master one-dimensional arrays in C. Learn declaration, initialization, zero-based indexing, traversal, linear search, bubble sort, and array parameter passing. This topic is essential for academic learning, board exam preparation, and developing optimized real-world code.

Mentor's Note: Imagine trying to write a program that stores the marks of 50 students in your class. If you use variables, you would have to declare int marks1, marks2, ..., marks50;. This would be a nightmare to write, manage, and search! In programming, we solve this by creating a contiguous block of storage called an Array. Think of it like a long chest of drawers labeled under one single name, where each drawer contains a value and is numbered! πŸ’‘

πŸ“š Educational Content: Working with arrays is a foundational concept in computer science. Arrays are tested heavily in GSEB Class 11/12 Practical Journals, CBSE Class 11/12 exams, and college BCA Sem 1 programming papers.

What You'll Learn

By the end of this tutorial, you'll know:

  • The concept of contiguous memory storage in arrays.
  • How to declare, initialize, and access one-dimensional (1D) arrays.
  • How to traverse arrays using loops for input and output.
  • How to implement search (Linear Search) and sorting (Bubble Sort) algorithms.
  • How to pass arrays to functions as parameters.

🌟 The Scenario: The Train Compartments​

Imagine a cargo train. Instead of manufacturing 5 separate, unconnected cars to ship steel, grain, oil, cars, and coal, the train company builds one single, connected train with 5 compartments.

  • The whole train has one name: cargo_train.
  • The compartments are connected sequentially (one after another).
  • To access the cargo, we use an index number starting from 0 up to 4.
  • cargo_train[0] holds steel, while cargo_train[4] holds coal.

In C programming:

  • The train is the Array.
  • The compartments are the Elements of the array.
  • The index numbers are the Subscripts (indices).
  • All compartments must hold the same type of items (you cannot put a liquid container directly into a flat coal bedβ€”all compartments must hold consistent data types).

πŸ“– Concept Explanation​

An array is a fixed-size, sequential collection of elements of the same data type stored in contiguous (neighboring) memory locations.

1. Memory Representation​

When you declare an array of size 5:

int numbers[5];

The compiler reserves 5 contiguous blocks of memory, each large enough to hold an integer (typically 4 bytes). If the first element numbers[0] is stored at memory address 1000, then:

  • numbers[1] is at address 1004
  • numbers[2] is at address 1008
  • numbers[3] is at address 1012
  • numbers[4] is at address 1016

2. Declaration & Initialization​

You must specify the data type, the array name, and the number of elements in square brackets:

int arr[5]; // Declares an array of 5 integers (contains garbage values initially)

You can initialize an array at the time of declaration:

int arr[5] = {10, 20, 30, 40, 50}; // Full initialization
int arr[] = {10, 20, 30}; // Compiler calculates size as 3 automatically
int arr[5] = {10, 20}; // Partial initialization: arr[0]=10, arr[1]=20, others become 0

3. Accessing Elements (Zero-based Indexing)​

In C, the first element is at index 0, and the last element is at index N - 1 (where $N$ is the size of the array).

int val = arr[0]; // Read first element
arr[4] = 99; // Write value 99 to the fifth element

🧠 Algorithm & Step-by-Step Logic​

Let's design the logic for Bubble Sort (which sorts an array in ascending order):

  1. Start 🏁
  2. Use nested loops: the outer loop runs from i = 0 to size - 2 (keeps track of passes).
  3. The inner loop runs from j = 0 to size - i - 2 (compares adjacent elements).
  4. If arr[j] > arr[j+1], swap them.
  5. Repeat until the array is fully sorted.
  6. End 🏁

πŸ’» Implementations​

We will write three essential programs showing array operations.

#include <stdio.h>

// Function to perform Linear Search
int linear_search(int arr[], int size, int target) {
for (int i = 0; i < size; i++) {
if (arr[i] == target) {
return i; // Target found, return index
}
}
return -1; // Target not found
}

int main() {
int numbers[] = {12, 45, 78, 23, 56};
int size = sizeof(numbers) / sizeof(numbers[0]);
int target = 23;

// Array traversal (printing elements)
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", numbers[i]);
}
printf("\n");

int result = linear_search(numbers, size, target);
if (result != -1) {
printf("Element %d found at index %d\n", target, result);
} else {
printf("Element %d not found in the array\n", target);
}
return 0;
}

// Output:
// Array elements: 12 45 78 23 56
// Element 23 found at index 3

2. Sorting an Array (Bubble Sort)​

#include <stdio.h>

void bubble_sort(int arr[], int size) {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - i - 1; j++) {
// Compare adjacent elements
if (arr[j] > arr[j + 1]) {
// Swap them
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

int main() {
int arr[] = {64, 34, 25, 12, 22};
int size = sizeof(arr) / sizeof(arr[0]);

printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");

bubble_sort(arr, size);

printf("Sorted array: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

// Output:
// Original array: 64 34 25 12 22
// Sorted array: 12 22 25 34 64

3. Passing Arrays to Functions​

#include <stdio.h>

// Function accepts array and its size
float calculate_average(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i]; // Accumulating sum
}
return (float)sum / size; // Type casting for float division
}

int main() {
int grades[] = {85, 90, 78, 92, 88};
int size = sizeof(grades) / sizeof(grades[0]);

float avg = calculate_average(grades, size);
printf("The average grade is %.2f\n", avg);
return 0;
}

// Output:
// The average grade is 86.60

πŸ“Š Sample Dry Run​

Let's dry run the inner comparisons of Bubble Sort on array [5, 2, 4] (size 3) for the first pass ($i=0$).

StepOuter Loop $i$Inner Loop $j$ComparisonActionArray StateDescription
100arr[0] > arr[1] (5 > 2)Swap[2, 5, 4]5 is larger than 2, so they swap places.
201arr[1] > arr[2] (5 > 4)Swap[2, 4, 5]5 is larger than 4, so they swap. Largest element is now at end.
30Inner loop ends ($j < 3 - 0 - 1 \implies j < 2$). First pass complete.

πŸ“‰ Complexity Analysis​

OperationTime Complexity ⏱️Space Complexity πŸ’ΎReason
Access$O(1)$$O(1)$Memory address calculated directly using base address and offset.
Linear Search$O(N)$$O(1)$Must traverse the array sequentially in the worst case.
Bubble Sort$O(N^2)$$O(1)$Contains nested loops comparing adjacent elements.

🎨 Visual Logic & Diagrams​

Here is how the array is stored contiguous in memory:


πŸ“š Best Practices & Common Mistakes​

βœ… Best Practices​

  • Dynamic Size Calculation: Use sizeof(arr) / sizeof(arr[0]) to find the number of elements in an array dynamically rather than hardcoding it.
  • Pass Array Size: Always pass the array size as a separate parameter to functions. Inside the function, the array decay prevents you from using sizeof to find its length.

❌ Common Mistakes βš οΈβ€‹

  • Off-by-One Errors: Accessing arr[size] when the valid indices are only 0 to size - 1.
  • Out of Bounds (Segmentation Fault): C does not check array bounds at runtime. Writing to arr[10] when size is 5 will overwrite other variables or crash the program.
  • Modifying Arrays Accidentally: Passing an array to a function passes its memory address. Any modifications inside the function will change the original array.

🎯 Practice Problems​

Easy Level πŸŸ’β€‹

  1. Write a program that inputs 5 numbers into an array from the user and prints their sum.
  2. Find the largest element in an array of size $N$.

Medium Level πŸŸ‘β€‹

  1. Write a program to reverse the elements of an array in place (without using a second array).
  2. Count the number of even and odd integers in an array.

Hard Level πŸ”΄β€‹

  1. Implement Binary Search on a sorted array of integers.
  2. Write a program that merges two sorted arrays into a single, sorted third array.

❓ Frequently Asked Questions​

Q: Why do C arrays start indexing at 0 instead of 1?

The index represents the offset (distance) from the start of the array in memory. The first element is located exactly at the base address, meaning its distance from the start is 0. The second element is located 1 integer width away from the start, so its index is 1.

Q: Can we change the size of a declared array at runtime in C?

No. Static C arrays have a fixed size defined at compile-time. If you want dynamic resizing, you must use dynamic memory allocation functions like malloc() and realloc().

Q: What does it mean when we say an array name is a pointer?

In C, the name of an array (e.g., numbers) points to the memory address of the first element (&numbers[0]). Because of this, arrays behave like reference parameters when passed to functions.


βœ… Summary​

In this tutorial, you've learned:

  • βœ… Arrays store lists of data of the same type in contiguous memory locations.
  • βœ… Array indices range from 0 to N - 1.
  • βœ… Traversal is done using a simple for loop from index 0 to size - 1.
  • βœ… Passing arrays to functions passes their base address, allowing direct changes.
  • βœ… C does not check array bounds, which can lead to memory bugs if you access invalid indices.

πŸ’‘ Interview Tips & Board Focus πŸ‘”β€‹

  • Board Exam Prep: You will often be asked to write programs to find the maximum/minimum value or search for an element in an array. Make sure you memorize the standard loop conditions.
  • Interview Question: "Why is array access $O(1)$?" Answer: "Because the computer calculates the element address directly using formula: Address = Base Address + Index * Data Type Size."
  • Key Terms: Subscript, Contiguous Memory, Array Decay, Bounds Checking.

πŸ“š Further Reading​

Continue your learning path:

Go deeper:

πŸ“ Visit Us

🏫 VD Computer Tuition Surat

VD Computer Tuition
πŸ“ Address
2/66 Faram Street, Rustompura
Surat – 395002, Gujarat, India
πŸ“ž Phone / WhatsApp
+91 84604 41384
🌐 Website

Computer Classes & Tuition β€” Areas We Serve in Surat

Adajanβ€’Althanβ€’Amroliβ€’Athwaβ€’Athwalinesβ€’Bhagalβ€’Bhatarβ€’Bhestanβ€’Canal Roadβ€’Chowkβ€’Citylightβ€’Dumasβ€’Gaurav Pathβ€’Ghod Dod Roadβ€’Haziraβ€’Jahangirpuraβ€’Kamrejβ€’Kapodraβ€’Katargamβ€’Limbayatβ€’Magdallaβ€’Majura Gateβ€’Mota Varachhaβ€’Nanpuraβ€’New Citylightβ€’Olpadβ€’Palβ€’Pandesaraβ€’Parle Pointβ€’Piplodβ€’Punaβ€’Randerβ€’Ring Roadβ€’Rustampuraβ€’Sachinβ€’Salabatpuraβ€’Sarthanaβ€’Sosyo Circleβ€’Udhnaβ€’Varachhaβ€’Ved Roadβ€’Vesuβ€’VIP Road
πŸ“ž Call SirπŸ’¬ WhatsApp Sir