- 2067 Asoj · 8 marks
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.
- Read n and the n elements into array A (declared larger than n, e.g. 100).
- Read the position POS (1 to n + 1) and the number NUM.
- 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. - Store NUM in
A(POS)and increase n by 1. - 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)
Related questions
- Insert value in array at position · Computer Programming, chapter 7
- Sort array ascending in FORTRAN · Computer Programming, chapter 11 · asked 2×
- Structure of a FORTRAN program · Computer Programming, chapter 11 · asked 5×
- Accessing array elements using pointer · Computer Programming, chapter 9
- Correct program: case array and average · Computer Programming, chapter 3
- Insert a string into another string · Computer Programming, chapter 7
- Prime number program: procedural and OOP · Object Oriented Programming, chapter 1
- Insert and delete kth node in doubly linked list · Data Structure and Algorithm, chapter 4 · asked 2×
- Function template: sum and average of array · Object Oriented Programming, chapter 9