Insert an element AT LAST available position in an array of size S

Insert an element at last available position in an array of size S.

Algorithm:

1.       START

2.       N = Get Total number of elements currently present in the array (A)

3.       Ele = Get a new element to insert

4.       If (N < S) then A[N] = Ele

5.       STOP

 

Implementation:

Scenario 1: Some elements are present.

Array A[10]. N=5. S=10

ARRAY BEFORE INSERTION:

15

20

26

78

25

 

 

 

 

 

 

1.       START

2.       N=5

3.       Ele = 13

4.       If(5<10), A[5] = 13

5.        STOP

 

ARRAY AFTER INSERTION:

15

20

26

78

25

13

 

 

 

 

 

Scenario 2: Array is empty.

Array A[10]. Size=10

ARRAY BEFORE INSERTION:

 

 

 

 

 

 

 

 

 

 

 

1.       START

2.       N=0

3.       Ele = 13

4.       If(0<10), A[0] = 13

5.        STOP

 

ARRAY AFTER INSERTION:

13

 

 

 

 

 

 

 

 

 

 

 

Scenario 3: Array is FULL.

Array A[10]. Size=10

ARRAY BEFORE INSERTION

15

20

26

78

25

27

36

97

12

69

 

1.       START

2.       N=10

3.       Ele = 13

4.       If(10<10) which is false hence no insertion

5.       STOP

 

ARRAY AFTER INSERTION

15

20

26

78

25

27

36

97

12

69

Insert an Element At Beginning of An Array

Insert an element at beginning position in an array of size S.

Algorithm:

1.       START

2.       N = Get Total number of elements currently present in the array (A)

3.       If N==0, goto 5

4.       If (N<S),  move all elements one position right, else goto 7

5.       Ele = Get a new element to insert

6.       A[0] = Ele

7.       STOP

 

Implementation:

Scenario 1: Some elements are present.

Array A[10]. N=5. S=10

ARRAY BEFORE INSERTION:

15

20

26

78

25

 

 

 

 

 

 

1.       START

2.       N=5

3.       N is not zero so goto next step (4).

4.       5<10, which is true, hence move all elements one position right. Array after step#4:

 

15

20

26

78

25

 

 

 

 

 

5.       Ele = 13

6.       A[0] = 13

7.        STOP

 

ARRAY AFTER INSERTION:

13

15

20

26

78

25

 

 

 

 

 

 

 

Scenario 2: Array is empty.

Array A[10]. Size=10

ARRAY BEFORE INSERTION:

 

 

 

 

 

 

 

 

 

 

 

1.       START

2.       N=0

3.       Since N is ZERO, going to 5

4.       <NOT EXECUTED>

5.       Ele = 13

6.       A[0] = 13

7.        STOP

 

ARRAY AFTER INSERTION:

13

 

 

 

 

 

 

 

 

 

 

 

Scenario 3: Array is FULL.

Array A[10]. Size=10

ARRAY BEFORE INSERTION

15

20

26

78

25

27

36

97

12

69

 

1.       START

2.       N=10

3.       N is not ZERO, so going to STEP#4

4.       If(10<10) which is false hence no insertion, going to STEP#7

5.       <NOT EXECUTED>

6.       <NOT EXECUTED>

7.       STOP

 

ARRAY AFTER INSERTION

15

20

26

78

25

27

36

97

12

69