简体   繁体   中英

How do I add up all the results from a for loop?

static void Main(string[] args)
{

    int five = 5;
    int sum = 0;

    for (int i = 0;   i < 1000; i++)
    {
        if (i % five == 0)
        {
            Console.WriteLine(i);
        }
    }
}

This simply prints out all the multiples of 5, that are less than 1000.

Is there any way I can add up all of the results of the for loop?

What means "add up"? You can add them to a collection like a List<int> :

List<int> multpiplesOf5 = new List<int>();
for (int i = 0; i < 1000; i++)
{
    if (i % 5 == 0)
    {
        multpiplesOf5.Add(i);
    }
}

If you want to output all you can loop them:

foreach(int i in multpiplesOf5)
    Console.WriteLine(i);

or use String.Join :

string result = String.Join(Environment.NewLine, multpiplesOf5);

Here is a concise LINQ version of the loop:

List<int> multpiplesOf5 = Enumerable.Range(0, 1000).Where(i => i % 5 == 0).ToList();

If you instead want to sum them up you can use the LINQ extension Enumerable.Sum :

int sumOfAll = multpiplesOf5.Sum();

If you want the count of numbers which were divisible by 5:

int count = multpiplesOf5.Count();

or without the list with a single LINQ query:

int count = Enumerable.Range(0, 1000).Count(i => i % 5 == 0);
 using System.Linq;

 var sumOfFives = Enumerable
   .Range(0, 1000)
   .Where(i => i % 5 == 0)
   .Sum();

If you mean to get the sum of all the numbers that are multiples 5 then

static void Main(string[] args)
{

    int five = 5;
    int sum = 0;

    for (int i = 0;   i < 1000; i++){

        if (i % five == 0)
        {
            sum += i;
        }

    }

    Console.WriteLine(sum);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM