Skip to main content

Array overflow/underflow; add two arrays

Short answer

Array overflow: accessing beyond last index (size-1) or inserting into full array; underflow: accessing before first index or deleting from empty. C does not check bounds, causing undefined behavior. The program checks n is within bounds (≤ MAX) before reading, then computes c[i]=a[i]+b[i] for each element.

What are overflow and underflow errors in context of array? Write a program to add corresponding elements of two arrays. The results should form a new array.

Overflow and underflow in arrays

  • Array overflow: trying to store or access an element beyond the last valid index (size − 1), for example writing a[10] in int a[10], or inserting into an array that is already full.
  • Array underflow: trying to access an element before the first one (index −1 or below), or deleting/removing an element from an empty array.

C does not check array bounds. Such access touches memory that belongs to other variables, which causes wrong results, corrupted data or a crash (undefined behaviour). The programmer must check the index or the element count before access (if (n < MAX) before insertion, if (n > 0) before deletion).

Program: add corresponding elements of two arrays

The size n is checked against the array limit (to avoid overflow) and c[i] = a[i] + b[i] forms the new array.

#include <stdio.h>
#define MAX 50

int main(void)
{
    int a[MAX], b[MAX], c[MAX], n;
    printf("Enter number of elements (1-%d): ", MAX);
    scanf("%d", &n);
    if (n < 1 || n > MAX) {              /* guard against overflow */
        printf("Invalid size\n");
        return 1;
    }
    printf("Enter elements of first array: ");
    for (int i = 0; i < n; i++)
        scanf("%d", &a[i]);
    printf("Enter elements of second array: ");
    for (int i = 0; i < n; i++)
        scanf("%d", &b[i]);

    for (int i = 0; i < n; i++)
        c[i] = a[i] + b[i];              /* corresponding elements */

    printf("Resultant array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", c[i]);
    printf("\n");
    return 0;
}

Sample run

Input: 4 1 2 3 4 10 20 30 40

Enter number of elements (1-50): Enter elements of first array: Enter elements of second array: Resultant array: 11 22 33 44

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 7 questions →