Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

[C#]Adding values to an array

  1. Jun 29, 2014 #1

    adjacent

    User Avatar
    Gold Member

    The title.
    A friend of me told me the code in php
    Code (Text):

    <?php
    for($i=0; $i<=100; $i++)
    {
         if($i%5==0)
         {
              $out[] = $i;
         }
    }  
    foreach($out as $val)
    {
       echo $val."<br>";
    }
    ?>
    The result is the multiples of 5 in the first 100.
    How do I reproduce this part:"$out[] = $i; " in C#?
    I have searched everywhere but couldn't find how to do that.
     
    Last edited: Jun 29, 2014
  2. jcsd
  3. Jun 29, 2014 #2
  4. Jun 29, 2014 #3

    adjacent

    User Avatar
    Gold Member

    Oh, thank you so much. This is my final code :smile:
    Code (Text):
    while (true)
                {
                    int limit;
                    int multiple;
                    Console.Write("Limit:");
                    int.TryParse(Console.ReadLine(), out limit);
                    Console.Write("Multiple:");
                    int.TryParse(Console.ReadLine(), out multiple);
                    List<int> no = new List<int>();
                    for (int i = 1; i <= limit; i++)
                    {
                        if (i % multiple == 0)
                        {
                            no.Add(i);
                        }
                    }

                    foreach (object o in no)
                    {
                        Console.WriteLine(o);
                    }
                }
     
  5. Jul 19, 2014 #4
    This code is inefficient. Out of many iterations of the loop, only a small number produce a useful result. Can you improve that, ideally so that every iteration results in a addition to the list?

    Further, can you use an array, as you seem to have wanted initially, rather than a list?

    Finally, if the goal is to output the numbers, do you really need to store them?
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: [C#]Adding values to an array
  1. Arrays c++ (Replies: 14)

  2. C++ Array (Replies: 10)

  3. C# arrays (Replies: 1)

Loading...