Click here to Skip to main content
15,894,294 members
Please Sign up or sign in to vote.
2.00/5 (2 votes)
See more:
can you help me to read the second value in array
i mean :
int [] marks = new int[5] { 99, 98, 92, 97, 95};
int [] marks1 = new int[5] { 13, 19, 5, 4, 2};
int [] marks2 = new int[5] { 9, 1, 17, 288, 14};
I want read just the second value from those arrays : 98 , 19 , 1
and put it in a new array how i can do it ? in for loop i mean
thank you .
Posted
Comments
[no name] 8-Jun-15 5:17am    
u just call the index of mark[1],mark1[2],etc
Matt T Heffron 8-Jun-15 12:18pm    
Don't you mean:
mark[1], ...
[no name] 8-Jun-15 23:55pm    
Yupz :)
Matt T Heffron 8-Jun-15 12:17pm    
This is pretty clearly only part of what you really are trying to accomplish...
If you can describe simply what the whole task is, then you may get even better advice than the two (pretty good) solutions, below.

In my opinion, getting the values from the array would be a very much good idea, like this,

C#
int[] arr = { marks[1], marks1[1], marks2[1] };


Enough. It would have an array of 3 elements having the value of second element in those three arrays.

Otherwise, if you want to get the values using the loop. You would write the loop and get the value using the index variable. But, remember, you only want one value so do not waste CPU cycles on extra loops. Write it this way,

C#
int a = 0;
for (int i = 1; i < 2; i++ ) { a = marks[i]; }


The above loop would run only once, because in the first time the condition would be true, then it would be false so after getting the value at index 1 (element 2) it would break. Write it this way,

C#
int[] arr = { 0, 0, 0 }; // arbitrary data (not required)

for (int i = 1; i < 2; i++) { arr[0] = marks[1]; }
for (int i = 1; i < 2; i++) { arr[1] = marks1[1]; }
for (int i = 1; i < 2; i++) { arr[2] = marks2[1]; }

// Possible value would be
{ 98, 19, 1 }


There you go.
 
Share this answer
 
v2
Why would you need a for loop?
C#
var result = new [] {marks[1],marks1[1],marks2[1]};

Edit
If you had the arrays in an array like this:
C#
var marksArray = new [] {marks, marks1, marks2};

Then you could use LINQ to create the result array:
C#
var result2 = marksArray.Select(x => x[1]).ToArray();

Using for-loop is just too much work.
 
Share this answer
 
v2

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