﻿ C# tutorial Loops-sum input values

# C# tutorial Loops-sum input values

## sum input values

Let see other C# code examples of using loops--for loop, while loop, and do while loops to enable a user to input a number of data points and then calculate the total of the data values. We provide three separate C# code examples to solve the same problem. One C# code example is using for loop and the two others are using while loop , and do while loop.

Example 1: C# code using for loop 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)
{

sumValues();

}

static void sumValues()
{

int sum = 0,val,n, i;
Console.Write("Enter number of data points:");
for (i = 0; i < n; i++)

{
Console.Write("Values " + i+":");
sum += val;
}

Console.WriteLine("Total:" + sum);

}

Example 2: C# code using while loop 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)

{
sumValues();

}

static void sumValues()

{
int sum = 0, val,n, i=0;
Console.Write("Enter number of data points:");
while (i<n)

{
Console.Write("Values " + i+":");
sum += val;
i += 1;

}

Console.WriteLine("Total:" + sum);

}

Example 3: C# code using do while loop 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)

{
sumValues();

}

static void sumValues()

{
int sum = 0, val,n, i=0;
Console.Write("Enter number of data points:");
do

{
Console.Write("Values " + i + ":");
sum += val;
i += 1;
}while (i < n);

Console.WriteLine("Total:" + sum);

}