Visual C# 8.16 (Using the foreach Statement)

This Solution is for the “Using the foreach Statement” of chapter 8 in the textbook; Visual c# How to program 6th edition by Deitel.

//Date: 5/25/2017

/*Description:
Uses foreach statement to sum the double values passed by the
command-line arguments.
*/
using System;

class Program
{
static void Main(string[] args)
{
// checks number of command-line arguments
if (args.Length < 3)
{
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(
“Error: Please re-enter the entire command,\n” +
“including 3 numbers to sum.”);
}
// checks number of command-line arguments
if (args.Length > 3)
{
Console.WriteLine();
Console.WriteLine();
Console.WriteLine(
“Error: Please re-enter the entire command,\n” +
“including ONLY 3 numbers to sum.”);
}
else
{
// gets values from command-line argument
var arg1 = double.Parse(args[0]);
var arg2 = double.Parse(args[1]);
var arg3 = double.Parse(args[2]);

//initializer list specifies the values of each element
double[] array = { arg1, arg2, arg3 };

//declares total
double total = 0.0;

// calculates value for each array element
foreach (double number in array)
{
total += number;
}

//prints sum
Console.WriteLine();
Console.WriteLine();
Console.WriteLine($”The Sum of array elements is: {total}”);

}
}
}

 Note: You MUST enter arguments in debug > properties before running this application. If your not sure how to do this check out my super quick tutorial on How To Use Command-Line Arguments In Visual C# 2015

 

Program Output: (using NO arguments)

Error: Please re-enter the entire command,
including 3 numbers to sum.

 

Program Output: (using arguments: 2, 3, 5.505, & 7)

The Sum of array elements is: 10.75

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s