Click here to Skip to main content
15,891,316 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i have array like

C#
int [] marks = new int[5]  { 99,  98, 95};

it means
now i want to insert marks 96 in 2rd postion i,e

what is the logic i have tried many ways please help

What I have tried:

C#
int [] marks = new int[5]  { 99,  98, 95};

it means
int[0]=99
int[1]=98
int[2]=95

now i want to insert marks 96 in 2rd postion i,e

int[0]=99
int[1]=98
int[2]=96
int[3]=95

what is the logic i have tried many ways please help
Posted
Comments
Dj@y 11-Feb-16 6:40am    
you can add that in to marks[2]= 96

You can't do that with an array. For this purpose, you might want to use a List<T>:
List(T) Class (System.Collections.Generic)[^]
C#
List<int> marks = new List<int>() { 99, 98, 95 }; // initialize a list with 3 values
marks.Insert(2, 96); // insert value '96' at index '2'
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 11-Feb-16 9:06am    
5ed.
—SA
Thomas Daniels 11-Feb-16 9:16am    
Thank you.
Inserting in an array is a little complicated - you have to move all the "higher index" values out of the way first and then save the value in the array.
[0 == 99][1 == 98][2 == 95][3 == empty]

[0 == 99][1 == 98][2 == 95][3 == 95]

[0 == 99][1 == 98][2 == 96][3 == 95]
That's complicated, because you have to first make sure there is enough room in the array, then work from the "high index end" and manually copy each value.

Instead, use a List<int> and you'll find it has an Insert method which does all that for you:
C#
List<int> marks = new List<int> { 99,  98, 95};
marks.Insert(2, 96);
 
Share this answer
 
Comments
F. Xaver 11-Feb-16 6:53am    
5ed
murkalkiran 29-Feb-16 0:01am    
what is 5ed?
OriginalGriff 29-Feb-16 5:40am    
It's a nod to the CodeProject reputation system.
If you look at the top of the solution I posted, there are "stars" on the right. At the moment it shows 4 orange, and one grey. That's an overall vote of "4 out of five" - and if you hover the mouse over them, it shows you that it's made up of 4 votes, three of them "5" (or "good answer") and one "1" (or "bad answer")
F.Xaver was telling me he thought it was a good answer, and that he voted "5" by clicking on the right hand end of the stars.
Every "up" vote adds to your reputation, every "down" votes takes some rep away.
It doesn't matter, it's not important: you can't swap rep points for cash! :laugh:

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900