- 2073 Shrawan · 2+4 marks
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]inint 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)
Related questions
- Add two matrices · Computer Programming, chapter 7
- Correct program: case array and average · Computer Programming, chapter 3
- Add and subtract matrices in FORTRAN · Computer Programming, chapter 11
- Accessing array elements using pointer · Computer Programming, chapter 9
- Correct program: character arrays · Computer Programming, chapter 7
- Two dimensional arrays in FORTRAN · Computer Programming, chapter 11
- Queue overflow and underflow errors · Data Structure and Algorithm, chapter 2
- 8085 ALP: add two tables, sum and carry · Microprocessor, chapter 2
- Antenna arrays and two-element expression · Propagation and Antenna, chapter 2
- Function overloading; new/delete average program · Object Oriented Programming, chapter 3