0

I have just started to learn to program in C# and I have created a very simple program that is suppose to summarize all positive numbers that's inside a int array.

The program looks something like this:

static void Main(string[] args)
{
    int[] intArr = new int[5] { 1, 2, 3, -1, 0 };
    int result = Sum(intArr);
    Console.WriteLine("The total sum of the array is: {0}", result);
    Console.ReadKey();
}

public static int Sum(int[] intArr)
{
    int sum = 0;
    for(int i =0; i < intArr .Length; i++)
    {
        if(values[i]>0)
        {
            sum += intArr[i];
        }
    }
     return sum;
}

Is there any way I can make this program any smaller or improve it's logic?

anderssinho
  • 298
  • 2
  • 7
  • 21

4 Answers4

2

You cannot improve much on the algorithm though. Since you are gonna sum up all the array elements, you need to iterate over each of them at least once, putting you at O(n) as the best you can do.

The code itself cannot be optimized much either. As regards making it smaller, you could consider using Linq and lambda expressions:

// ...
int result = intArr.Where(i => i > 0).Sum();

The lambda expression (i => i > 0) in conjunction with Where() sets a predicate (condition) which tells the program to sum all elements (i) where i is a positive integer (=> i > 0).

But that negates the purpose of writing your own function. If that's not necessary you can even use a one-liner:

Console.WriteLine("The total sum of the array is: {0}", new int[] { 1, 2, 3, -1, 0 }.Where(i => i > 0).Sum());

Also, since you're initializing the array with values, mentioning the array length isn't necessary as demonstrated above. Not really an optimization, just a tip.

Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
1

For typical enumerable operations you can use LINQ. Since you can chain operators, you can pretty easily filter first and then sum.

Using common LINQ operators means the code is more readable and maintanable than handwritten snippets.

int[] intArr = new int[5] { 1, 2, 3, -1, 0 };

int result = intArr.Where( i => i > 0 ).Sum();

Console.WriteLine(result);
Wiktor Zychla
  • 47,367
  • 6
  • 74
  • 106
1

Using static imports and string interpolation

using static System.Math;
using System.Linq;
using static System.Console;
namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine($"The total sum of the array is: { new[] { 1, 2, 3, -1, 0 }.Sum(x => Max(0, x))}");
            ReadKey();
        }
    }
}

More readable with additional variable:

var total = new[] { 1, 2, 3, -1, 0 }.Sum(x => Max(0, x));
WriteLine($"The total sum of the array is: {total}");
AxCoder
  • 638
  • 5
  • 11
0

You can improve the code using lambda expressions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            int[] intArr = new int[5] { 1, 2, 3, -1, 0 };
            int result =  intArr.AsParallel().Where(i => i > 0).Sum();
            Console.WriteLine("The total sum of the array is: {0}", result);
        }
    }
}

If the length of the array is big it could be useful use AsParallel() in order to divide the array and share the sum operation between the processing cores.

https://www.dotnetperls.com/asparallel

manelseo
  • 587
  • 4
  • 6
  • 1
    You'll have to provide an example of what you mean, it doesn't seem clear where OP should use a lambda expressions (or how it would improve the code) – UnholySheep Mar 10 '18 at 13:17
  • Done. On the other hand the best optimization of this code is show directly the result, because the elements are always the same elements... The result is always the same :) – manelseo Mar 10 '18 at 15:38