How Can I Replicate PHP Array Addition in C#?

  • Context: C# 
  • Thread starter Thread starter adjacent
  • Start date Start date
  • Tags Tags
    Array
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 5K views
adjacent
Gold Member
Messages
1,552
Reaction score
62
The title.
A friend of me told me the code in php
Code:
<?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:
Physics news on Phys.org
DrZoidberg said:
Use the List class.
http://msdn.microsoft.com/en-us/library/6sh2ey19(v=vs.110).aspx

Code:
List<int> out= new List<int>();
...
out.Add(i);
Oh, thank you so much. This is my final code :smile:
Code:
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);
                }
            }
 
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?