foreach loop

passing values to an array

Page 1 of 1

4 Replies - 1182 Views - Last Post: 31 March 2009 - 09:08 PM Rate Topic: -----

#1 munnap  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 13-November 08

foreach loop

Posted 26 November 2008 - 06:09 AM

how to use the foreach loop in a program to pass the values to an array in runtime

{
foreach(int k in n)
console.readline();
}
isn't this correct?






***Changed thread title***
-jjsaw5
Is This A Good Question/Topic? 0
  • +

Replies To: foreach loop

#2 zakary  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 27
  • View blog
  • Posts: 427
  • Joined: 15-February 05

Re: foreach loop

Posted 26 November 2008 - 06:14 AM

no here is an example of a foreach

ArrayList array = new ArrayList();

array.Add("Test1");
array.Add("Test2");
array.Add("Test3");
array.Add("Test4");

foreach(string value in array)
{
Console.WriteLine(value);
}



output will be
Test1
Test2
Test3
Test4

This post has been edited by zakary: 26 November 2008 - 06:15 AM

Was This Post Helpful? 0
  • +
  • -

#3 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1511
  • View blog
  • Posts: 5,916
  • Joined: 21-March 08

Re: foreach loop

Posted 26 November 2008 - 08:16 AM

I would use a ForEach loop for this ONLY if it was absolutely required. It is much easier to write values into an array using a For loop:

string[] array = new string[5];
for (int i = 0; i < array.Length; i++)
{
      array[i] = Console.ReadLine();
}

//using a ForEach to print them out is fine
foreach (string s in array)
{
      Console.WriteLine(s);
}

Console.ReadLine();


Was This Post Helpful? 0
  • +
  • -

#4 jjsaw5  Icon User is offline

  • I must break you
  • member icon

Reputation: 88
  • View blog
  • Posts: 3,056
  • Joined: 04-January 08

Re: foreach loop

Posted 26 November 2008 - 08:19 AM

Please use more descriptive and helpful thread titles. C# is not what we consider a good thread title.
Was This Post Helpful? 0
  • +
  • -

#5 gever  Icon User is offline

  • New D.I.C Head

Reputation: 4
  • View blog
  • Posts: 29
  • Joined: 19-June 08

Re: foreach loop

Posted 31 March 2009 - 09:08 PM

foreach (string day in week)
{
MessageBox.Show("The day is : " + day);
}

http://csharp.net-in...oreach-loop.htm

tks.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1