• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Insertion Of Element in Array

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

 
Bartender
Posts: 2236
63
IntelliJ IDE Firefox Browser Spring Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
If somebody says you look familiar, tell them you are in porn. Or in these tiny ads:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic