How to calculate the sum of all the even numbers in one-dimensional int array in C#

1 Answer

0 votes
using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                int[] arr = { 1, 2, 3, 4, 5, 6, 7 };
                int sum = 0;

                for (int i = 0; i < arr.Length; i++)
                    if (arr[i] % 2 == 0)
                        sum += arr[i];

                Console.WriteLine("sum = " + sum);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

/*
run:
   
sum = 12
  
*/

 



answered Feb 8, 2016 by avibootz
...