Yorda
Yorda

Reputation: 15

Sum of selected values in an int Array in c#

I'm learning how to program using c#. I'm really new to this. My question is I'm trying to create an array that shows 10 numbers. I want my code to check which numbers below 10 are divisible for 3 or 5 and sum the total. I've tried to use the .Sum() function but says int doesn't contain a definition for Sum. I've put using System.Linq on my program. Does anyone have an idea how to make this sum happens?

        {

            int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            int sum = 1 + 2;
            

            foreach (int n in numbers)
            {
                if (n % 3 == 0 || n % 5 == 0)
                {
                    int total = n.Sum();
                     Console.WriteLine(total);
                }
                else
                {
                    Console.WriteLine("not divisible");
                }
            }`
   

Upvotes: 0

Views: 2265

Answers (3)

dennis_ler
dennis_ler

Reputation: 676

If I understand it correct and using your code this is what you want.

        int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        int sum = 1 + 2;
        int total=0;

        foreach (int n in numbers)
        {
            if (n % 3 == 0 || n % 5 == 0)
            {
                int total += n;
            }
            else
            {
                Console.WriteLine("not divisible");
            }
        }
        Console.WriteLine(total);

I moved the printing out to after the foreach so you get one result when it is done

Upvotes: 0

Serge
Serge

Reputation: 43860

Everybody forgot that array should contain 10 numbers but some numbers values maybe greater than 10. Only number values below 10 should be checked. So a right answer should be

var numbers = new int[] { 1, 9, 5, 6, 8, 10,4, 15, 25, 3};
var total = numbers.Where( n => (n<10) && ( n % 3 == 0 || n % 5 == 0)).Sum();

Upvotes: 0

zaitsman
zaitsman

Reputation: 9499

So your problem is that you are trying to call .Sum() on a variable n which is of type int (you define it here: foreach (int n in numbers), and that is not a method.

Using LINQ you could do something like:

var numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var total = numbers.Where(n => n % 3 == 0 || n % 5 == 0).Sum();

Upvotes: 1

Related Questions