Thursday, October 29, 2026

Passing Arrays to Pattern Functions in C | Advanced Concepts

Passing Arrays to Pattern Functions in C | Advanced Concepts

Introduction

Pattern programming in C is an excellent way to develop logical thinking and understand fundamental programming concepts. As patterns become more complex, however, writing all the logic inside the main() function can make programs difficult to read, maintain, and reuse.

A better approach is to divide a program into smaller, reusable functions.

In C, arrays can be passed to functions so that the functions can access their elements and use them to generate different patterns. This approach combines two important concepts: array manipulation and function-based programming.

By passing arrays to pattern functions, programmers can separate data from presentation, reuse the same array for multiple patterns, and create modular programs that are easier to test and maintain.

In this article, we will explore how arrays are passed to functions in C, how array sizes are handled, and how to implement different patterns using reusable functions.

1. Understanding How Arrays Are Passed to Functions in C

Consider the following array:

int arr[] = {1, 2, 3, 4, 5};

Suppose we want to print its elements using a separate function.

We can define a function that accepts a pointer to the first element of the array and the number of elements to process.

#include <stdio.h>

void printArray(const int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%d ", arr[i]);
    }

    printf("\n");
}

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

    printArray(arr, n);

    return 0;
}

Output

1 2 3 4 5

Explanation

The function declaration is:

void printArray(const int arr[], int n)

Here:

  • const int arr[] allows the function to read the array elements without modifying them.

  • int n specifies how many elements the function should process.

  • void indicates that the function does not return a value.

In a function parameter declaration, const int arr[] is adjusted to const int *arr. The function receives a pointer to the first element, not a separate copy of the entire array.

This distinction is important because the function cannot determine the original array's length using sizeof(arr) inside the function. That is why the length is passed separately.

Key concept: When passing a one-dimensional array to a function, pass its size explicitly so the function knows how many elements it can safely access.

2. Why Use Functions for Pattern Programming?

In a basic pattern program, all loops and calculations are often placed inside main(). This is acceptable for small examples, but it becomes less practical when a program supports multiple patterns.

Consider a program that generates triangular patterns, reverse triangles, palindromic patterns, and other arrangements using the same data.

Without functions, each pattern's logic must be written directly in the main program. With functions, each pattern can be implemented independently.

The main advantages include:

  • Code reusability: A pattern function can be called multiple times with different arrays.

  • Modularity: Each function performs a clearly defined task.

  • Maintainability: Changes to one pattern do not require rewriting unrelated logic.

  • Readability: The main function becomes shorter and easier to understand.

  • Testability: Each pattern can be tested independently.

The following examples demonstrate these advantages through practical C programs.

3. Pattern 1: Printing an Array in Triangular Form Using a Function

Let us create a function that accepts an array and prints its elements in a right-angled triangular pattern.

Expected output

10
10 20
10 20 30
10 20 30 40
10 20 30 40 50

C program

#include <stdio.h>

void printTriangle(const int arr[], int n)
{
    for (int i = 1; i <= n; i++)
    {
        for (int j = 0; j < i; j++)
        {
            printf("%d ", arr[j]);
        }

        printf("\n");
    }
}

int main(void)
{
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);

    printTriangle(arr, n);

    return 0;
}

Explanation

The function printTriangle() receives two arguments: the array and its length.

The outer loop controls the rows, while the inner loop determines how many elements to print in each row.

In the first row, only arr[0] is printed. In the second row, the first two elements are printed. This continues until the final row contains all five elements.

The function does not need to know how the array was created. It only requires a valid pointer to the first element and the correct number of elements.

This makes the function reusable with other arrays of the same type.

For example, calling printTriangle() with an array containing {2, 4, 6, 8} would generate the same structure with different values.

Time complexity: (O(n^2)), because the function prints (n(n+1)/2) elements.

Space complexity: (O(1)) auxiliary space.

4. Pattern 2: Printing an Array in Reverse Triangular Form

The same array can be used to generate a reverse triangular pattern through another function.

Expected output

10 20 30 40 50
10 20 30 40
10 20 30
10 20
10

C program

#include <stdio.h>

void printReverseTriangle(const int arr[], int n)
{
    for (int i = n; i > 0; i--)
    {
        for (int j = 0; j < i; j++)
        {
            printf("%d ", arr[j]);
        }

        printf("\n");
    }
}

int main(void)
{
    int arr[] = {10, 20, 30, 40, 50};
    int n = sizeof(arr) / sizeof(arr[0]);

    printReverseTriangle(arr, n);

    return 0;
}

Explanation

The outer loop begins at n and decreases to 1.

During each iteration, the inner loop prints the first i elements of the array. Consequently, each successive row contains one fewer element than the preceding row.

Notice that the array is declared as const int arr[] in the function parameter. This communicates that the function only reads the supplied elements and does not modify them.

Key concept: Multiple functions can operate on the same array to generate different patterns without duplicating the underlying data.

Time complexity: (O(n^2)).

5. Pattern 3: Generating a Palindromic Numeric Pattern Using a Function

A palindromic numeric pattern increases toward a central value and then decreases symmetrically.

Expected output

1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

C program

#include <stdio.h>

void printPalindrome(const int arr[], int n)
{
    for (int i = 1; i <= n; i++)
    {
        /* Print ascending sequence */
        for (int j = 0; j < i; j++)
        {
            printf("%d ", arr[j]);
        }

        /* Print descending sequence */
        for (int j = i - 2; j >= 0; j--)
        {
            printf("%d ", arr[j]);
        }

        printf("\n");
    }
}

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

    printPalindrome(arr, n);

    return 0;
}

Explanation

The function constructs each row using two inner loops.

The first loop prints the first i elements in ascending index order. The second loop prints the preceding elements in reverse order.

For example, when i is 4, the first loop prints:

1 2 3 4

The second loop prints:

3 2 1

Together, they form the row:

1 2 3 4 3 2 1

The descending loop starts at i - 2 because the largest element has already been printed. Starting at i - 1 would duplicate the central element.

Key concept: Passing an array to a function allows the pattern logic to be separated from the initialization of the data.

Time complexity: (O(n^2)).

6. Pattern 4: Generating Floyd's Triangle Using a Function

Floyd's Triangle arranges consecutive integers in increasing order across successive rows.

Expected output

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

For this example, the function will receive an array containing consecutive integers and print them in triangular form.

C program

#include <stdio.h>

void printFloydTriangle(const int arr[], int n)
{
    int index = 0;

    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= i; j++)
        {
            printf("%d ", arr[index]);
            index++;
        }

        printf("\n");
    }
}

int main(void)
{
    int arr[15];
    int value = 1;
    int index = 0;
    int n = 5;

    /* Populate the array */
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= i; j++)
        {
            arr[index++] = value++;
        }
    }

    /* Generate the pattern */
    printFloydTriangle(arr, n);

    return 0;
}

Explanation

The program separates data generation from pattern display.

First, the nested loops populate the array with consecutive integers. The variable index identifies the next available array position, while value tracks the next integer to store.

Once the array is populated, printFloydTriangle() receives the array and the number of rows.

The function maintains its own index and prints one element in the first row, two in the second, and so on.

The total number of elements required for n rows is:

[
\frac{n(n+1)}{2}
]

For five rows, the program requires 15 integers.

Important: The function assumes that the array contains at least n(n+1)/2 elements. The caller must ensure that this requirement is satisfied.

Key concept: Functions can operate on prepared array data, allowing data generation and pattern formatting to be developed and tested independently.

Time complexity: (O(n^2)) for generating and printing the pattern.

7. Pattern 5: Passing a Two-Dimensional Array to a Function

So far, the examples have used one-dimensional arrays. However, many advanced patterns involve matrices and two-dimensional arrays.

In C, a function that accepts a two-dimensional array with a fixed column count can be declared as follows:

void printMatrix(int rows, int arr[][4])

The compiler needs to know the column dimension to calculate the address of each row.

Let us use this technique to print a matrix.

Expected output

1   2   3   4
5   6   7   8
9  10  11  12
13 14  15  16

C program

#include <stdio.h>

void printMatrix(int rows, const int arr[][4])
{
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < 4; j++)
        {
            printf("%-4d", arr[i][j]);
        }

        printf("\n");
    }
}

int main(void)
{
    int arr[4][4] = {
        {1,  2,  3,  4},
        {5,  6,  7,  8},
        {9, 10, 11, 12},
        {13, 14, 15, 16}
    };

    printMatrix(4, arr);

    return 0;
}

Explanation

The function accepts the number of rows and a two-dimensional array with four columns.

The expression arr[i][j] accesses the element at row i and column j.

Unlike a one-dimensional array parameter, a multidimensional array parameter must provide the dimensions needed to calculate element addresses. In this example, the column count is fixed at four.

The const qualifier ensures that the function does not modify the matrix elements through this parameter.

Key concept: Two-dimensional arrays can be passed to functions, but the function declaration must provide the required column dimension.

Time complexity: (O(r \times c)), where r is the number of rows and c is the number of columns.

8. Pattern 6: Passing Array Dimensions to Generate a Matrix Pattern

A reusable matrix function should ideally support different row counts and column counts.

One approach is to use a variable-length array parameter, supported by C99 and some later C implementations. This approach allows the column count to be supplied at runtime.

C program

#include <stdio.h>

void printMatrix(int rows, int cols,
                 const int arr[rows][cols])
{
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            printf("%4d", arr[i][j]);
        }

        printf("\n");
    }
}

int main(void)
{
    int arr[3][4] = {
        {1,  2,  3,  4},
        {5,  6,  7,  8},
        {9, 10, 11, 12}
    };

    printMatrix(3, 4, arr);

    return 0;
}

Explanation

The function receives the number of rows and columns before the array parameter.

The declaration:

const int arr[rows][cols]

allows the function to use the supplied dimensions to access the matrix elements.

This makes the function more flexible than the previous example, which was limited to four columns.

However, the dimensions must match the actual matrix layout. The function does not independently verify that the supplied dimensions describe the memory passed by the caller.

Key concept: Passing dimensions explicitly allows matrix functions to support different array sizes without hardcoding the column count.

Portability note: Variable-length arrays are supported by C99, but implementations may omit them in later C standards. Check the compiler and language standard used by your project.

9. Pattern 7: Creating a Reusable Pattern Function with a Pointer

Since an array parameter is adjusted to a pointer parameter, the following declaration is also valid:

void printTriangle(const int *arr, int n)

This form explicitly communicates that the function receives a pointer to the first integer.

C program

#include <stdio.h>

void printTriangle(const int *arr, int n)
{
    for (int i = 1; i <= n; i++)
    {
        for (int j = 0; j < i; j++)
        {
            printf("%d ", *(arr + j));
        }

        printf("\n");
    }
}

int main(void)
{
    int arr[] = {2, 4, 6, 8, 10};
    int n = sizeof(arr) / sizeof(arr[0]);

    printTriangle(arr, n);

    return 0;
}

Output

2
2 4
2 4 6
2 4 6 8
2 4 6 8 10

Explanation

The expression:

*(arr + j)

is equivalent to:

arr[j]

Both access the element at index j.

The pointer-based declaration makes the relationship between array parameters and pointers explicit. It also provides an opportunity to practice pointer arithmetic without changing the overall pattern logic.

In most cases, arr[j] is easier to read, so pointer arithmetic should be used when it improves the clarity of the example or illustrates a specific concept.

Key concept: Array notation and pointer notation can be used interchangeably for element access within a valid array.

10. Important Rules When Passing Arrays to Functions

When writing array-based pattern functions, keep the following rules in mind.

10.1 Pass the array length separately

A function cannot reliably determine the original length of an array from its adjusted array parameter.

Calculate the length at the calling site:

int n = sizeof(arr) / sizeof(arr[0]);

This works when arr is an actual array in the current scope, not when it is an array parameter.

10.2 Use const for read-only functions

If a pattern function only displays array elements, use a parameter such as:

void printPattern(const int arr[], int n)

This prevents accidental modification of elements through that parameter.

10.3 Understand that array elements are not copied automatically

Passing an array to a function does not create an independent copy of all its elements. The function receives access to the original array through a pointer.

If the function modifies an element, the modification is visible to the caller.

10.4 Validate dimensions and storage requirements

Ensure that the supplied length and dimensions accurately describe the array. Every index must remain within the valid bounds.

For dynamically allocated arrays, check allocation failures and release the allocated memory when it is no longer required.

10.5 Keep pattern logic independent of data initialization

A well-designed pattern function should focus on arranging and displaying data rather than creating the input values unnecessarily.

For example, a triangle-printing function can accept different arrays and produce the same structure for each one.

This separation improves reusability and makes testing easier.

11. Common Mistakes to Avoid

The following mistakes frequently occur when passing arrays to functions in C:

  • Using sizeof() incorrectly: The size of an array parameter is the size of a pointer, not the size of the original array.

  • Passing the wrong length: An incorrect length may cause the function to access elements outside the array.

  • Assuming arrays are passed by value: The function receives a pointer to the original elements, not a separate array copy.

  • Using incorrect matrix dimensions: The column count must be consistent with the actual two-dimensional array layout.

  • Modifying read-only data: Use const when the function should not modify elements.

  • Duplicating pattern logic: Prefer reusable functions over repeating the same nested loops in multiple places.

  • Ignoring empty or invalid input: Handle zero or negative row counts according to the requirements of the program.

  • Confusing pattern dimensions with array dimensions: The number of rows in a displayed pattern may differ from the number of elements stored in the array, so the required capacity must be calculated carefully.

12. Practice Problems

Try implementing the following exercises to reinforce your understanding.

Beginner level

  1. Write a function that prints an array in right-angled triangular form.

  2. Create a function that prints an array in reverse triangular order.

  3. Pass an integer array to a function that prints a palindromic numeric pattern.

Intermediate level

  1. Write a function to print Floyd's Triangle using a pre-populated array.

  2. Create a function that accepts an array and prints its elements in alternating ascending and descending row lengths.

  3. Pass a two-dimensional array to a function that prints a matrix row by row.

  4. Write a function that accepts an array and prints only its even-valued elements in a triangular pattern.

Advanced level

  1. Generate Pascal's Triangle and separate its construction from its printing logic.

  2. Create a reusable function that prints a matrix in spiral order.

  3. Write a matrix-pattern function that accepts runtime row and column dimensions.

  4. Implement a function that accepts a pointer and an element count to print a symmetric numeric pattern.

  5. Design a collection of pattern functions that use a shared array to produce multiple output formats.

For every exercise, focus on the function's parameters, the relationship between the array and its dimensions, and the correctness of the loop boundaries.

Conclusion

Passing arrays to pattern functions in C is an important step toward writing modular, reusable, and maintainable programs. Instead of placing every loop and calculation inside main(), programmers can define functions that accept array data and generate specific patterns independently.

Through triangular patterns, palindromic sequences, Floyd's Triangle, and matrix printing, we have seen how array parameters simplify the separation of data and presentation. We have also explored pointer-based array parameters, two-dimensional arrays, and the importance of passing dimensions explicitly.

The central principle is simple: a well-designed pattern function should clearly define what data it receives, how much data it can access, and how that data is arranged in the output.

Mastering these techniques will help you progress from isolated pattern programs to structured C applications that use reusable functions, arrays, and pointers effectively.


For all Pattern Programs list click here: 

…till the next post, bye-bye & take care  

No comments:

Post a Comment