Back to C Programming
2025-12-205 min read

4.2 An Example with Arrays (C Programming)

Learn 4.2 An Example with Arrays (C Programming) step by step with clear examples and exercises.

Title: Mastering Arrays in C Programming - A full guide

Why This Matters

Arrays are fundamental data structures in C programming, enabling efficient storage and manipulation of large sets of data. Understanding arrays is crucial for tackling complex problems, debugging real-world issues, and acing coding interviews. Arrays provide a means to store multiple values of the same data type in a single variable, making them an essential tool for managing data efficiently.

Prerequisites

Before diving into arrays, it's essential to have a solid foundation in:

  1. Basic C syntax (variables, operators, control structures)
  2. Understanding of memory management in C
  3. File I/O operations in C
  4. Familiarity with pointer concepts and their usage in C
  5. Knowledge of data types and their properties in C
  6. Comprehension of mathematical operations in C
  7. Understanding of conditional statements and loops

Core Concept

An array is a collection of elements of the same data type stored contiguously in memory. The elements are accessed using an index that starts at 0.

int arr[5]; // Declaring an array of 5 integers
arr[0] = 10; // Assigning the first element a value of 10

Arrays can be initialized with values during declaration:

int arr[] = {1, 2, 3, 4, 5}; // Initializing an array with values

You can also determine the size of an array at runtime using sizeof() function.

Array Operations

  • Accessing elements: arr[index]
  • Changing element values: arr[index] = value
  • Finding the length of an array: sizeof(arr) / sizeof(arr[0])
  • Iterating through arrays using pointers:
int arr[] = {1, 2, 3, 4, 5};
int i;
for (i = 0; i < sizeof(arr) / sizeof(arr[0]); ++i) {
printf("%d ", arr[i]);
}

Array Sizes and Dynamic Memory Allocation

  • Static arrays have a fixed size at compile time.
  • Dynamic memory allocation allows for creating arrays of varying sizes during runtime using functions like malloc().

Worked Example

Let's create a simple program that calculates the average of numbers stored in an array.

#include <stdio.h>

int main() {
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
int n = sizeof(arr) / sizeof(arr[0]); // Calculate array length

for (int i = 0; i < n; ++i) {
sum += arr[i];
}

double avg = (double)sum / n;
printf("Average: %.2f\n", avg);

return 0;
}

Common Mistakes

  1. Forgetting to initialize an array: This can lead to undefined behavior when accessing elements.
int arr[5]; // Uninitialized array
printf("%d\n", arr[0]); // Outputs garbage value
  1. Accessing out-of-bounds elements: This can cause segmentation faults or unexpected results.
int arr[] = {1, 2, 3};
printf("%d\n", arr[3]); // Segmentation fault
  1. Not considering the array length when iterating: Forgetting to account for the array size can lead to skipping elements or accessing out-of-bounds elements.
int arr[] = {1, 2, 3};
for (int i = 0; i < 4; ++i) { // Iterating past the end of the array
printf("%d\n", arr[i]);
}
  1. Misunderstanding array sizes and dynamic memory allocation: Incorrect use of dynamic memory allocation can lead to memory leaks or overwriting memory.
int *arr; // Declaring a pointer to an integer
arr = malloc(5 * sizeof(int)); // Allocating memory for 5 integers
arr[0] = 10; // Assigning the first element a value of 10
free(arr); // Forgetting to free allocated memory can lead to a memory leak

Common Mistakes (Continued)

  1. Not checking for array bounds when using dynamic memory allocation: Failing to check if memory was successfully allocated or not can result in uninitialized pointers and segmentation faults.
int *arr; // Declaring a pointer to an integer
arr = malloc(5 * sizeof(int)); // Allocating memory for 5 integers
if (arr == NULL) { // Check if allocation was successful
printf("Memory allocation failed.\n");
return 1;
}
  1. Not freeing dynamically allocated memory: Failing to free dynamically allocated memory can lead to memory leaks.
int *arr = malloc(5 * sizeof(int)); // Allocating memory for 5 integers
// ...
free(arr); // Freeing the allocated memory
  1. Not considering array size when using dynamic memory allocation: Incorrectly calculating the size of dynamically allocated memory can lead to insufficient or excessive memory allocation.
int *arr = malloc(5 * sizeof(int)); // Allocating memory for 5 integers
// ...
free(arr); // Freeing the allocated memory
  1. Using integer values with character arrays: Assigning an integer value to a character array element will result in undefined behavior, as the array is intended for storing characters.
char arr[5] = "Hello"; // Correct usage
arr[6] = 7; // Undefined behavior

Practice Questions

  1. Write a program that finds the maximum number in an array.
  2. Create a program that sorts an array of integers using bubble sort.
  3. Implement a function that searches for a specific value in an array and returns its index if found, or -1 otherwise.
  4. Implement a function that dynamically allocates memory for an array of integers and initializes it with user-provided values.
  5. Write a program that calculates the sum of all even numbers in an array.
  6. Implement a function that swaps two elements in an array without using a temporary variable.
  7. Create a program that reverses the order of elements in an array.
  8. Write a program that finds the second largest number in an array.
  9. Implement a function that merges two sorted arrays into a single sorted array.
  10. Write a program that counts the occurrences of each unique character in a string stored as an array of characters.
  11. Create a program that finds the smallest positive integer missing from an unsorted array of integers.
  12. Implement a function that returns the kth largest number in an array.
  13. Write a program that checks if an array contains duplicates and prints them if present.
  14. Implement a function that rotates an array by a given number of positions.
  15. Create a program that finds the first repeating element in a circular array.

FAQ

How do I declare a multidimensional array in C?

A multidimensional array can be declared as follows:

int arr[3][4]; // Declares a 3x4 matrix of integers

What happens if I try to assign an integer value to a character array element?

Assigning an integer value to a character array element will result in undefined behavior, as the array is intended for storing characters.

char arr[5] = "Hello"; // Correct usage
arr[6] = 7; // Undefined behavior

How do I free dynamically allocated memory in C?

To free dynamically allocated memory, use the free() function:

int *arr = malloc(5 * sizeof(int));
// ...
free(arr); // Freeing the allocated memory