Progress: 10 of 16 topics62%

Arrays in C Programming

Arrays are a fundamental data structure in C programming that allow you to store multiple values of the same type under a single variable name. They provide an efficient way to organize and access large amounts of data. In this tutorial, you'll learn how to create, manipulate, and effectively use arrays in your C programs.

What You'll Learn

  • What arrays are and why they're useful
  • How to declare and initialize arrays
  • Accessing and modifying array elements
  • Common array operations and patterns
  • Arrays and memory concepts
  • Passing arrays to functions
  • Common pitfalls and best practices

What is an Array?

An array is a collection of elements of the same data type, stored in contiguous memory locations. You can think of an array as a row of boxes, each containing a value, and each box has a unique index (position number) to identify it.

Array Visualization

10
25
8
16
42
37
index 0
index 1
index 2
index 3
index 4
index 5

Array name: numbers

Type: int

Size: 6 elements

Why Use Arrays?

Efficient Storage

Store multiple related values using a single variable name instead of creating multiple separate variables.

Sequential Access

Access elements sequentially with loops, making it easy to process large amounts of data with compact code.

Random Access

Access any element directly using its index, providing quick and efficient data retrieval.

Memory Efficiency

Arrays are stored in contiguous memory locations, making them more efficient than individually allocated variables.

Array Declaration and Initialization

Before using an array, you need to declare it by specifying its data type and size.

Array Declaration

The basic syntax for declaring an array is:

c
1dataType arrayName[arraySize];
2
3// Examples
4int numbers[10]; // An array of 10 integers
5float prices[50]; // An array of 50 floating-point numbers
6char name[20]; // An array of 20 characters

Array Initialization

There are several ways to initialize arrays in C:

c
1// Method 1: Initialize at declaration with specific values
2int scores[5] = {90, 85, 75, 95, 88};
3
4// Method 2: Initialize with fewer values than the array size
5// Remaining elements will be initialized to 0
6int counts[10] = {1, 2, 3}; // Only first 3 elements are initialized, rest are 0
7
8// Method 3: Let the compiler determine the size based on initialization
9int values[] = {10, 20, 30, 40, 50}; // Size is automatically set to 5
10
11// Method 4: Initialize all elements to zero
12int zeros[100] = {0}; // All 100 elements will be 0
13
14// Method 5: Initialize after declaration (one by one)
15int data[5];
16data[0] = 10;
17data[1] = 20;
18data[2] = 30;
19data[3] = 40;
20data[4] = 50;

Important Array Rules

  • Arrays are zero-indexed in C (the first element is at index 0)
  • The array size must be a constant expression or a constant value
  • All array elements must be of the same data type
  • Array size cannot be changed after declaration
  • C doesn't check array bounds - accessing beyond the array limits leads to undefined behavior

Accessing Array Elements

You can access and modify individual array elements using their index within square brackets:

c
1#include <stdio.h>
2
3int main() {
4 int numbers[5] = {10, 20, 30, 40, 50};
5
6 // Accessing array elements
7 printf("First element: %d\n", numbers[0]); // 10
8 printf("Third element: %d\n", numbers[2]); // 30
9 printf("Last element: %d\n", numbers[4]); // 50
10
11 // Modifying array elements
12 numbers[1] = 25;
13 numbers[3] = 45;
14
15 printf("Modified second element: %d\n", numbers[1]); // 25
16 printf("Modified fourth element: %d\n", numbers[3]); // 45
17
18 return 0;
19}
20
21// Output:
22// First element: 10
23// Third element: 30
24// Last element: 50
25// Modified second element: 25
26// Modified fourth element: 45

Iterating Through Arrays

A common operation with arrays is to iterate through all elements using a loop:

c
1#include <stdio.h>
2
3int main() {
4 int scores[5] = {85, 92, 78, 90, 88};
5 int sum = 0;
6 float average;
7
8 // Iterate through the array to calculate sum
9 for (int i = 0; i < 5; i++) {
10 sum += scores[i];
11 printf("Score %d: %d\n", i + 1, scores[i]);
12 }
13
14 // Calculate average
15 average = (float)sum / 5;
16
17 printf("\nSum of all scores: %d\n", sum);
18 printf("Average score: %.2f\n", average);
19
20 return 0;
21}
22
23// Output:
24// Score 1: 85
25// Score 2: 92
26// Score 3: 78
27// Score 4: 90
28// Score 5: 88
29//
30// Sum of all scores: 433
31// Average score: 86.60

Common Array Operations

Finding the Maximum and Minimum Values

c
1#include <stdio.h>
2
3int main() {
4 int numbers[8] = {42, 15, 67, 33, 19, 88, 7, 50};
5 int max = numbers[0]; // Assume first element is maximum
6 int min = numbers[0]; // Assume first element is minimum
7
8 // Find maximum and minimum values
9 for (int i = 1; i < 8; i++) {
10 if (numbers[i] > max) {
11 max = numbers[i];
12 }
13
14 if (numbers[i] < min) {
15 min = numbers[i];
16 }
17 }
18
19 printf("Array: ");
20 for (int i = 0; i < 8; i++) {
21 printf("%d ", numbers[i]);
22 }
23
24 printf("\nMaximum value: %d\n", max);
25 printf("Minimum value: %d\n", min);
26
27 return 0;
28}
29
30// Output:
31// Array: 42 15 67 33 19 88 7 50
32// Maximum value: 88
33// Minimum value: 7

Searching for an Element

c
1#include <stdio.h>
2
3int main() {
4 int numbers[10] = {12, 45, 67, 23, 9, 56, 89, 32, 78, 41};
5 int searchValue = 56;
6 int position = -1; // -1 indicates not found
7
8 // Linear search
9 for (int i = 0; i < 10; i++) {
10 if (numbers[i] == searchValue) {
11 position = i;
12 break; // Exit the loop once found
13 }
14 }
15
16 if (position != -1) {
17 printf("%d found at index %d\n", searchValue, position);
18 } else {
19 printf("%d not found in the array\n", searchValue);
20 }
21
22 return 0;
23}
24
25// Output:
26// 56 found at index 5

Reversing an Array

c
1#include <stdio.h>
2
3int main() {
4 int original[5] = {10, 20, 30, 40, 50};
5 int reversed[5];
6
7 printf("Original array: ");
8 for (int i = 0; i < 5; i++) {
9 printf("%d ", original[i]);
10 }
11
12 // Reverse the array
13 for (int i = 0; i < 5; i++) {
14 reversed[i] = original[4 - i];
15 }
16
17 printf("\nReversed array: ");
18 for (int i = 0; i < 5; i++) {
19 printf("%d ", reversed[i]);
20 }
21
22 return 0;
23}
24
25// Output:
26// Original array: 10 20 30 40 50
27// Reversed array: 50 40 30 20 10

Arrays and Memory

Understanding how arrays are stored in memory is crucial for effective C programming:

Array Memory Layout

int[0]
int[1]
int[2]
int[3]
addr
addr+4
addr+8
addr+12

• Elements are stored in contiguous memory locations

• Each int element typically occupies 4 bytes of memory

• The array name (without brackets) is the address of the first element

The array name without brackets represents the base address (memory location of the first element). This relationship between arrays and memory addresses is why arrays and pointers are closely related in C.

Memory Facts About Arrays

  • The total memory used by an array = size of each element × number of elements
  • The address of element arr[i] = base address + (i × size of each element)
  • C does not perform bounds checking, so accessing outside the array bounds can cause errors or unexpected behavior
  • When an array is declared inside a function, it's stored on the stack (unless declared static)

Passing Arrays to Functions

When passing an array to a function, you're actually passing a pointer to the first element of the array. This means functions can modify the original array elements.

c
1#include <stdio.h>
2
3// Function to display array elements
4void displayArray(int arr[], int size) {
5 printf("Array elements: ");
6 for (int i = 0; i < size; i++) {
7 printf("%d ", arr[i]);
8 }
9 printf("\n");
10}
11
12// Function to double each element in the array
13void doubleArrayElements(int arr[], int size) {
14 for (int i = 0; i < size; i++) {
15 arr[i] = arr[i] * 2;
16 }
17}
18
19int main() {
20 int numbers[5] = {1, 2, 3, 4, 5};
21
22 printf("Original ");
23 displayArray(numbers, 5);
24
25 doubleArrayElements(numbers, 5);
26
27 printf("After doubling ");
28 displayArray(numbers, 5);
29
30 return 0;
31}
32
33// Output:
34// Original Array elements: 1 2 3 4 5
35// After doubling Array elements: 2 4 6 8 10

Important Notes About Arrays and Functions

  • You must pass the array size separately since the function doesn't know the array size
  • Functions can change the original array elements because they receive the memory address
  • When declaring function parameters, int arr[] and int* arr are equivalent

Arrays and Strings

In C, strings are essentially character arrays with a special terminating character (null character: '\0') to mark the end of the string.

c
1#include <stdio.h>
2
3int main() {
4 // String as a character array
5 char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
6
7 // Simplified string initialization (null character is added automatically)
8 char message[] = "Hello";
9
10 printf("Greeting: %s\n", greeting);
11 printf("Message: %s\n", message);
12
13 return 0;
14}
15
16// Output:
17// Greeting: Hello
18// Message: Hello

We'll cover strings in more detail in the dedicated strings tutorial.

Common Pitfalls and How to Avoid Them

Array Index Out of Bounds

Accessing elements outside the array's valid range can cause unpredictable behavior or crashes.

Avoid by:

  • Always check array bounds before accessing elements
  • Use variables for array size and check against them

Not Initializing Arrays

Uninitialized array elements contain garbage values that can lead to incorrect program behavior.

Avoid by:

  • Always initialize arrays when declaring them
  • Use 0 to initialize all elements to zero

Forgetting Array Size Limits

Assuming arrays can grow beyond their declared size can lead to memory corruption.

Avoid by:

  • Use symbolic constants or #define for array sizes
  • Plan array sizes carefully before implementation

Returning Local Arrays from Functions

Arrays created inside functions are destroyed when the function exits, making pointers to them invalid.

Avoid by:

  • Pass arrays to functions for modification
  • Use dynamically allocated memory (malloc) if returning arrays
  • Declare arrays as static in functions if they must be returned

Practice Exercises

🎯 Try these exercises:

  1. Write a program to calculate the sum and average of array elements.
  2. Create a function to count how many times a specific number appears in an array.
  3. Implement a program to merge two sorted arrays into a single sorted array.
  4. Write a function to remove duplicate elements from an array.
  5. Create a program that rotates array elements to the left by a specified number of positions.

Summary

In this tutorial, you've learned about arrays in C programming:

  • Arrays are collections of elements of the same data type stored in contiguous memory
  • They provide an efficient way to store and access multiple related values
  • Arrays are declared with a specific size that can't be changed later
  • Elements are accessed using zero-based indexing: array[0] is the first element
  • Arrays can be passed to functions, which receive a pointer to the first element
  • C doesn't check array bounds, so careful index management is important
  • Character arrays are used to represent strings in C

Arrays are a cornerstone data structure in C programming, and mastering them is essential for developing efficient and well-structured programs. As you progress, you'll learn about more complex data structures built upon the array concept.

Related Tutorials

Functions in C

Learn about creating reusable code blocks in C programming.

Continue learning

Strings in C

Understand how to work with text data in C.

Continue learning

Pointers in C

Master pointers, a powerful feature in C programming.

Continue learning