Skip to main content

Insert number at position in array

Short answer

Shift all elements from POS to N one place right using a backward loop (I = N down to POS), then store the number at A(POS) and increment N. Validity checks ensure position is between 1 and N+1 and array size is not exceeded.

Write a program in FORTRAN to take a position and a number and insert this number on this position inside an array containing n elements.

Method.

  1. Read n and the n elements into array A (declared larger than n, e.g. 100).
  2. Read the position POS (1 to n + 1) and the number NUM.
  3. Starting from the last element, move each element from POS to n one place to the right (A(I+1) = A(I) for I = n down to POS). The loop runs backwards (step −1) so no value is overwritten.
  4. Store NUM in A(POS) and increase n by 1.
  5. Print the new array.
      PROGRAM INSERT
      INTEGER A(100), N, POS, NUM, I
      PRINT *, 'ENTER NUMBER OF ELEMENTS'
      READ *, N
      PRINT *, 'ENTER THE ELEMENTS'
      READ *, (A(I), I = 1, N)
      PRINT *, 'ENTER POSITION AND NUMBER TO INSERT'
      READ *, POS, NUM
      IF (POS .LT. 1 .OR. POS .GT. N+1 .OR. N .GE. 100) THEN
         PRINT *, 'INSERTION NOT POSSIBLE'
         STOP
      END IF
      DO 10 I = N, POS, -1
         A(I+1) = A(I)
   10 CONTINUE
      A(POS) = NUM
      N = N + 1
      PRINT *, 'NEW ARRAY:'
      PRINT *, (A(I), I = 1, N)
      STOP
      END

Sample: array 10 20 30 40 50, position 3, number 99 gives 10 20 99 30 40 50.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 11 questions →