I am trying to Sum the ASCII values for each character in a string. The last number printed out is the only one I want displayed. So if I enter "chris" I get back 99, 203, 317, 422 and 537. 537 is the correct value I want to display, how do I print out 537 only?
using System;
namespace BLConsoleApp
{
class Program
{
static void Main(string[] args)
{
bool executeLoop = true;
while (executeLoop)
{
Console.WriteLine("Please enter a word for the sum of it's ASCII value !!!");
Console.WriteLine("Type the word 'exit' at any time to escape ...");
string word = Console.ReadLine();
if (word != "EXIT" || word != "Exit" || word != "exit")
{
int sum = 0;
foreach (char c in word)
{
sum += c;
Console.WriteLine((int)sum);
}
}
if (word == "EXIT" || word == "Exit" || word == "exit")
{
executeLoop = false;
return;
}
}
}
}
}
WriteLine
out of the loop and write thesum
after the loop is completed.Console.WriteLine
statement outside theforeach
loopif (word.Equals("exit", StringComparison.OrdinalIgnoreCase))
. And instead of doing the comparison more than once, just use anelse
.