-2

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;
                }
            }
        }
    }
}
3
  • 4
    Just take the WriteLine out of the loop and write the sum after the loop is completed.
    – Rufus L
    Apr 23, 2019 at 16:44
  • move the Console.WriteLine statement outside the foreach loop
    – Matt.G
    Apr 23, 2019 at 16:44
  • 1
    Also, you can do a case-insensitive comparison like: if (word.Equals("exit", StringComparison.OrdinalIgnoreCase)). And instead of doing the comparison more than once, just use an else.
    – Rufus L
    Apr 23, 2019 at 16:46

1 Answer 1

0

You can simply put the WriteLine after the loop, so it only writes the final sum. Also, you can just use true as the condition for your loop, since return will break out of the loop immediately. Additionally, you can use the string.Equals method to do a case-insensitive comparison:

while (true)
{
    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.Equals("exit", StringComparison.OrdinalIgnoreCase))
    {
        return;
    }

    int sum = 0;

    foreach (char c in word)
    {
        sum += c;
    }

    Console.WriteLine(sum);
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.