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();
Console.ReadLine();
}
static void sumValues()
{
int sum = 0,val,n, i;
Console.Write("Enter number of data points:");
n = int.Parse(Console.ReadLine());
for (i = 0; i < n; i++)
{
Console.Write("Values " + i+":");
val = int.Parse(Console.ReadLine());
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();
Console.ReadLine();
}
static void sumValues()
{
int sum = 0, val,n, i=0;
Console.Write("Enter number of data points:");
n = int.Parse(Console.ReadLine());
while (i<n)
{
Console.Write("Values " + i+":");
val = int.Parse(Console.ReadLine());
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();
Console.ReadLine();
}
static void sumValues()
{
int sum = 0, val,n, i=0;
Console.Write("Enter number of data points:");
n = int.Parse(Console.ReadLine());
do
{
Console.Write("Values " + i + ":");
val = int.Parse(Console.ReadLine());
sum += val;
i += 1;
}while (i < n);
Console.WriteLine("Total:" + sum);
}
|
|
-
Why and How to learn
- C programming language?
- C++ programming language?
- C# programming language?
- Java programming language?
- Python programming language?
- VB programming language?
|
|