C# tutorial- Arrays: sum all elements of an integer array

sum all elements of an integer array

In this page, we provide one more C# code example that sums all elements of an integer array.
To sum all elements of an array you need to use a loop to traverse through the array(using every index). Each element of the array will be cumulated in to a variable. For the C# code example below, we allow a user to input a number of his/her data points then the program will display the total of the data set.

Example: C# code to sum all elements of an integer array

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

namespace ConsoleApplication1
class Program

static void Main(string[] args)



static void sumArray()

  int sum=0,n,i=0;
  Console.Write ("Enter number of data points:");
  n=int.Parse(Console.ReadLine()) ;
  int[] arr=new int[n];
     Console.Write ("Values[{0}",i+"]:");
     arr[i]=int.Parse (Console.ReadLine() ) ;
    } while(i<n);
  Console.WriteLine ("Total:{0}",sum);



Yanyong comment


It tested the code. It worked.


This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.