Arrays

Hosea

New member
Joined
Oct 1, 2013
Messages
1
Programming Experience
Beginner
Hi

I am learning programing, C# and I am on Arrays part. So I have this code and I don't understand.
static void Main(string[] args)
{
int[] n = new int[10];
int i, j;


//initialize elements of array n
for (i = 0; i < 10; i++)
{
n = i + 100;
}


/* output each array element's value */
for (j = 0; j < 10; j++)
{
Console.WriteLine("Element [{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}

Firstly I would like to know, how can I return values of i for loop, without using j for loop.. and why j for loop was used to display output.


 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,282
Location
Sydney, Australia
Programming Experience
10+
The first loop is used to put values into the array and the second is used to get the values out of the array and display them. In your terms, the j for loop IS returning the values of the i for loop. You could do away with j and use i as the counter for both loops if you wanted but the author of the code is simply trying to differentiate between the two operations: input and output.

Normally, when you want to get the data out of an array you won't have just put the data into it yourself using a loop like that. You'll have obtained the array from some other source. For instance, if you had a file Names.txt that contained this data:
Peter
Paul
Mary
then you might do this:
static void Main(string[] args)
{
    var names = File.ReadAllLines("Names.txt");

    for (var i = 0; i < names.Length; i++)
    {
        Console.WriteLine("Name [{0}] = {1}", i, names[i]);
    }

    Console.ReadLine();
}
 
Top Bottom