1

The objective of this code is to add all the integers in a whole number into one value (e.g "2013" => 6), In c# I have written the code so it outputs the number to its corresponding ASCII value one at a time, but I am at a loss at how to convert it back into its number value.

Note that I am new at C#

        string Year;
        int Total = 0;
        int Adding = 0;
        int Adding2 = 0;

        Console.WriteLine("Write The year you want converted");
        Year = Console.ReadLine();

        for (int i = 0; i < Year.Length; i++)
        {
            Adding2 = Year[i];
            Adding = Convert.ToInt32(Adding2);
            Total = Adding + Total;
            
            Console.WriteLine(Total);
        }
0

2 Answers 2

3

You should sum values, not ascii codes:

    ...

    for (int i = 0; i < Year.Length; i++)
    {
        Adding2 = Year[i];
        Adding = Adding2 - '0';
        Total = Adding + Total;
    }

    Console.WriteLine(Total);

In general case, you can use char.GetNumericValue():

    // double: some characters have fractional values: '⅝'
    double Total = 0.0;

    foreach (char c in Year) {
      double value = char.GetNumericValue(c);

      // If character has value (e.g. 'A' doesn't have) 
      if (value != -1)
        Total += value;
    } 

    Console.WriteLine(Total);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that both approaches would need explicit input validation for the cases of non-digits in a real application, as they otherwise give nonsensical results without complaining.
0

Just little tweak to your code, will get the result

string Year;
int Total = 0;

Console.WriteLine("Write The year you want converted");
Year = Console.ReadLine();

for (int i = 0; i < Year.Length; i++)
{
    //  IN ASCII 
    //  48 means => number 0
    //  49 => 1
    //  .
    //  .
    //  58 => 10
    // So you need to subtract 48 from ascii value to get actual number
    Total = (Year[i] - 48) + Total;
}
Console.WriteLine(Total);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.