• Post Reply Bookmark Topic Watch Topic
  • New Topic

Insertion Of Element in Array  RSS feed

 
Mohammad Rehan
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can somebody please correct me here where I have gone wrong in this program to insert an array element at the specified position:

I tried this but got the undesired output :
Enter no. of Array elements
3
ENter elements :
1
2
3
Enter position of insertion
0
Enter elements to be inserted
0
Array elements after insertion
0
1
1
1

 
Paweł Baczyński
Bartender
Posts: 2054
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have added a print statement in your loop.
This is the result I got:

Enter no. of Array elements
10
ENter elements :
1
2
3
4
5
6
7
8
9
10
Enter position of insertion
0
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0]
[1, 1, 3, 4, 5, 6, 7, 8, 9, 10, 0]
[1, 1, 1, 4, 5, 6, 7, 8, 9, 10, 0]
[1, 1, 1, 1, 5, 6, 7, 8, 9, 10, 0]
[1, 1, 1, 1, 1, 6, 7, 8, 9, 10, 0]
[1, 1, 1, 1, 1, 1, 7, 8, 9, 10, 0]
[1, 1, 1, 1, 1, 1, 1, 8, 9, 10, 0]
[1, 1, 1, 1, 1, 1, 1, 1, 9, 10, 0]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 0]
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0]
Enter element to be inserted
999
Array elements after insertion
[999, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]


Can you see what is happening?
This value 1 was copied from index:
0 to 1
1 to 2
2 to 3
3 to 4 and so on...

Also, you never set a value on index n.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!