-1

Why does the code add up all the elements of the arr array just by using sum += x doesn't that mean " 0 = 0 + x"?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SoloLearn
{
    class Program
 {
    static void Main(string[] args)
    {
        int[ ] arr = {11, 35, 62, 555, 989};
        int sum = 0; 
        
        foreach (int x in arr) {
            sum += x;
        }
        Console.WriteLine(sum);
       }
   }
      }
canton7
  • 37,633
  • 3
  • 64
  • 77
calister28
  • 43
  • 4
  • 2
    On the first iteration of that loop, it expands to `x = x + 11`, or `x = 0 + 11`, which sets `x` to 11. On the *second* iteration of the loop, `x` has the value 11, and so it's `x = x + 35`, or `x = 11 + 35`, which sets `x` to 46. Note that `=` is the *assignment* operator: it evaluates the right-hand side, and sets this value to the variable named on the left-hand side. It's not quite equivalent to the mathematical "is equal to" symbol – canton7 Dec 16 '20 at 13:14
  • @canton7 You should turn that into an answer. – EricSchaefer Dec 16 '20 at 13:26
  • @EricSchaefer Eh, answers to low-quality questions, which are probably dups, tend to get downvoted. – canton7 Dec 16 '20 at 13:26

1 Answers1

-1

It is to initialize the sum parameter to start with 0 and to add to it the number in the array.

In C# the default value of int is 0 so the row can also be: int sum;

itzick binder
  • 524
  • 10
  • 31
  • "*In C# the default value of int is 0 so the row can also be: int sum;*" -- no it can't. Locals must always be initialized (fields don't have to be) – canton7 Dec 16 '20 at 15:42